0

假设一个对象,例如:

class A {
  string Country;
  string Region;
}

IEnumerable<A>比如:

    "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...

我如何获得一个IDictionary<string, IEnumerable<string>> reswith Linq whereres['Country']将返回一个IEnumerable<string>相应区域?

4

2 回答 2

6

ToLookup应该给你你想要的。

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

从技术上讲,它是不可变的,因此不实现IDictionary. 如果实现该接口很重要,那么您需要将查找转换为字典:

var dictionary = lookup.ToDictionary(group => group.Key, 
    group => group.AsEnumerable());
于 2013-09-25T17:46:28.437 回答
3
IDictionary<string, IEnumerable<string>> dictionary =
    list.GroupBy(r => r.Country)
    .ToDictionary(grp => grp.Key, grp => grp.Select(t => t.Region));
于 2013-09-25T17:48:01.400 回答