如何使用 Linq 获取多次满足键的字典

本文关键字:满足 字典 何使用 Linq 获取 | 更新日期: 2023-09-27 18:32:57

假设一个对象,例如:

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

如何使用 Linq 获取IDictionary<string, IEnumerable<string>> res,其中res['Country']将返回相应区域的IEnumerable<string>

如何使用 Linq 获取多次满足键的字典

ToLookup应该给你你想要的。

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

从技术上讲,它是不可变的,因此不会实现IDictionary。 如果必须实现该接口,则需要将查找转换为字典:

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));