简体   繁体   中英

How to get a dictionary with Linq where keys are met more than once?

Assuming an object such as:

class A {
  string Country;
  string Region;
}

And an IEnumerable<A> such as:

    "Denmark", "Arhus"
    "Denmark", "Bornholm"
    "Denmark", "Frederiksborg"
    "Denmark", "Fyn"
    "Denmark", "Copenhagen"
    "Denmark", "Nordjylland"
    "France", "Alsace"
    "France", "Aquitaine"
    "France", "Auvergne"
    "France", "Basse-Normandie"
    "France", "Bourgogne"
    "France", "Bretagne"
    "France", "Centre"
    "France", "Champagne-Ardenne"
    "France", "Corse"
    etc...

How can I obtain an IDictionary<string, IEnumerable<string>> res with Linq where res['Country'] would return an IEnumerable<string> of the corresponding regions ?

ToLookup should give you exactly what you want.

var lookup = data.ToLookup(a => a.Country, a=> a.Region);

Technically it's immutable, and as such doesn't implement IDictionary . If it's essential that you implement that interface then you'll need to convert the lookup to a dictionary:

var dictionary = lookup.ToDictionary(group => group.Key, 
    group => group.AsEnumerable());
IDictionary<string, IEnumerable<string>> dictionary =
    list.GroupBy(r => r.Country)
    .ToDictionary(grp => grp.Key, grp => grp.Select(t => t.Region));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM