user610217
user610217

Reputation:

Linq Expression to Organize (sorta like Group By but different)

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.

Upvotes: 1

Views: 112

Answers (3)

Anders Abel
Anders Abel

Reputation: 69270

IList<Foo> foos = //whatever

var groups = foos.ToLookup(f => f.Region);

An ILookup<T> is like dictionary, but each key references a list of values instead of just one.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502016

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.

Upvotes: 7

Lee
Lee

Reputation: 144176

IList<Foo> foos = //whatever
var groups = foos
    .GroupBy(f => f.Region)
    .ToDictionary(grp => grp.Key, grp => grp.ToList());

Upvotes: 1

Related Questions