markzzz
markzzz

Reputation: 47947

How can I GroupBy this LINQ query?

This is my code :

objectList = (from MyObject obj in MyObjects
             select r).ToList();

I'd like to return the list of each record with a "distinct" obj.ID. How can I do this?

Upvotes: 5

Views: 91

Answers (2)

ie.
ie.

Reputation: 6101

This gives you the list of type IGrouping<int, MyObject> (note, I assume that ID has type int):

groupedList = (from obj in MyObjects
             group obj by obj.ID into grouped
             select grouped).ToList();

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499810

It sounds like you might want ToLookup:

var lookup = MyObjects.ToLookup(x => x.ID);

That lets you fetch all the values for any particular ID, or iterate over the groupings. It's eagerly evaluated, rather than GroupBy's lazy evaluation, which is probably what you want in this case.

That's assuming I understood your request correctly - it's entirely possible that I didn't... it would be helpful if you could clarify.

Upvotes: 2

Related Questions