tags:

views:

140

answers:

4

Hi Guys

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?

A: 

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

Hexxagonal
Yes, there is.
mquander
Enter the great and powerful LINQ! :P
jrista
+10  A: 

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();
mquander
A: 

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); 
        }
Sam Saffron
A: 

thanx sambo99

i have decided using linq,i have already had your wroten code.

mquander.

your linq solition is great.thanx u very much.

tobias