2

I have a List<T> where T is a custom object Cow. Right now I use the following code to split that list up based on Color.

cowGroups = from x in cows
            group x by x.Color into y
            select y.ToList().ToList();

Then I take cowGroups and run a foreach on it to do a set of actions to each Cow. This list actually comes out as IEnumerable<List<Cow>>

What I'm trying to do is do a double grouping on my initial List<Cow> so that I can group base on their color and size. The result should still be IEnumerable<List<Cow>>, but each List<Cow> would be made based on the combined pair of color and size.

A co-worker recommended a ToLookup approach, but that returns a list of key/value pairs, and I can't seem to do anything with the value part of the pair.

I guess I'm looking for either a way to go straight to a collection of lists, or turn the result of the ToLookup approach into a collection of lists.

1 Answer 1

5

You can group by a class that contains both attributes:

group x by new { x.Color, x.Size } into y
Sign up to request clarification or add additional context in comments.

1 Comment

Oh my... I feel so stupid now. One of the things I had tried was `cows.GroupBy(new {x.Color, x.Size}) but it resulted in a similar structure as ToLookup. EDIT: I should add that this is exactly what I needed. Thank you!

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.