Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I GroupBy this LINQ query?

Tags:

c#

.net

linq

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?

like image 334
markzzz Avatar asked Oct 08 '22 11:10

markzzz


2 Answers

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();
like image 174
ie. Avatar answered Oct 10 '22 00:10

ie.


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.

like image 37
Jon Skeet Avatar answered Oct 10 '22 02:10

Jon Skeet