Let's say I have a fairly large IList<foo>
where foo
looks like this:
public class foo
{
public string Region { get; set; }
public string Territory { get; set; }
public string Location { get; set; }
public string Person { get; set; }
}
...is there a way, using a reasonably quick/ efficient expression, to "group" these foo items by Region
, so I might end up with an IDictionary<string, IList<foo>>
and have the string
key be the Region
property, with each subordinate IList<foo>
containing only the foo
records that match that region? (it would not have to be an IDictionary
, that's just to illustrate the gist of what I'm trying to do.) I want to present an interactive list to my MVC view organized this sort of way, without having to write something relatively complex or use a third-party library.
Yes - you want a Lookup
:
var lookup = list.ToLookup(x => x.Region);
You can create a dictionary by grouping, but personally I prefer to use a lookup as it's specifically designed for the "single key, multiple values" scenario.