tags:

views:

43

answers:

3

I have a sample class like this:

SampleClass
{
    string code;
    int id;
    string name;    
}

Valid data for the class would be:

SampleClass{code= "code1", id= 1, name= "name1"}
SampleClass{code= "code1", id= 1, name= "name2"}
SampleClass{code= "code2", id= 2, name= "name1"}
SampleClass{code= "code2", id= 2, name= "name2"}
SampleClass{code= "code2", id= 2, name= "name3"}

Now the question is, by using LINQ, I need to create a TestClass collection grouped on the SampleClass "id" field.

TestClass structure is as follows:

TestClass
{
    string code;        
    List<string> names;    
}

where "names" is a list of all SampleClass "name" values grouped by "id".

Based on the above SampleClass sample data, I would have 2 TestClass objects, one for id=1 and other for id=2

Thanks in advance

+3  A: 
var result = from c in collection
             group c by c.id into g
             select new TestClass {
                                      code = g.First().code,
                                      names = g.Select(i => i.name).ToList()
                                  };

ps: I have no VS near now, and I hope I did not make a lot of mistakes there :-)

zerkms
This will mean that the TestClass.code is the SampleClass.id, rather than the SampleClass.code.
Alastair Pitts
This almost works, except TestClass.names needs to be a list/enumerable of SampleClass not a list of strings for this to work.
Michael Shimmins
@Alastair Pitts: yes, thanks for correction
zerkms
+2  A: 

MSDN has some great LINQ examples, including using the Grouping to do just what you need. You can find an example doing something similar to what you want here.

davisoa
+3  A: 

OK, if you have an IEnumerable of SampleClasses called classes, try this:

        var testClasses = classes
            .GroupBy(c => c.id)
            .Select(grp => new TestClass
            {
                code = grp.First().code,
                names = grp.Select(c => c.name).ToList()
            });
Alastair Pitts
Deleted my answer - this one actually does the list of names rather than a list of SampleClasses as the value of `names`.
Michael Shimmins
Indeed, this answer is better than mine, since I've mixed up chain enumerable extensions and sql-like syntax. +1 ;-)
zerkms
@zerkms: Why thank you sir /bows
Alastair Pitts
I've just said your answer is good, why so ironic :-(
zerkms
@zerkms: No irony at all, it was genuinely a thank you :) (I could understand how that reads ironically)
Alastair Pitts