0

i have an array below

string stringArray = new stringArray[12];

stringArray[0] = "0,1";
stringArray[1] = "1,3";
stringArray[2] = "1,4";
stringArray[3] = "2,1";
stringArray[4] = "2,4";
stringArray[5] = "3,7";
stringArray[6] = "4,3";
stringArray[7] = "4,2";
stringArray[8] = "4,8";
stringArray[9] = "5,5";
stringArray[10] = "5,6";
stringArray[11] = "6,2";

i need to transform like below

List<List<string>> listStringArray = new List<List<string>>();

listStringArray[["1"],["3","4"],["1","4"],["7"],["3","2","8"],["5","6"],["2"]];

how is that possible?

3
  • 1
    Im not following what you want this transformation to do ... how does the input relate to the output? Commented May 26, 2009 at 15:44
  • 1
    I'm pretty sure that he wants the output to be grouped together by the first number in the input strings (i.e. "1, 3" and "1, 4" get put into the same bucket.) Commented May 26, 2009 at 15:46
  • Ahh, so there is a typo in the input data it should start with "1,1" Commented May 26, 2009 at 15:51

3 Answers 3

10

I think what you actually want is probably this:

var indexGroups = x.Select(s => s.Split(',')).GroupBy(s => s[0], s => s[1]);

This will return the elements as a grouped enumeration.

To return a list of lists, which is what you literally asked for, then try:

var lists = x.Select(s => s.Split(',')).GroupBy(s => s[0], s => s[1])
             .Select(g => g.ToList()).ToList();
Sign up to request clarification or add additional context in comments.

Comments

0

There's no shorthand like that. You'll have to break into a loop and split each array and add to the list.

1 Comment

Enter the great and powerful LINQ! :P
0

Non LINQ version (I must admit its much uglier, but you may have no choice)

        var index = new Dictionary<string, List<string>>();
        foreach (var str in stringArray) {
            string[] split = str.Split(',');
            List<string> items;
            if (!index.TryGetValue(split[0], out items)) {
                items = new List<string>();
                index[split[0]] = items;
            }
            items.Add(split[1]); 
        }

        var transformed = new List<List<string>>();
        foreach (List<string> list in index.Values) {
            transformed.Add(list); 
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.