使用重复键从DB查询创建C#字典

时间:2015-03-12 11:00:33

标签: c# dictionary

我有一个学校数据库,每个学校都在一个城市。 现在我想创建一个包含每个schoool的所有城市的字典。为此,我尝试了这种方法:

var schoolCities = schoolsWithAddresses.Where(school => school.Address.City != null).ToDictionary(sc => sc.Address.City.Name.ToLower());

现在,问题在于一个城市可以拥有多所学校。所以,当我创建我的字典时,我最终会遇到异常"重复密钥"。

我想创建一个dicitonary,因为它可以让我快速查找有学校的城市(这就是为什么我没有使用List,例如)。

如何以某种方式克服这个问题,让我仍能进行有效的查找?

5 个答案:

答案 0 :(得分:1)

您应该先对项目进行分组,以便拥有独特的城市。

schoolsWithAddresses.Where(school => school.Address.City != null)
.GroupBy(s => s.Address.City, (k, v) => new { City = k, Schools = v })
.ToDictionary(d => d.City, e => e.Schools)
;

答案 1 :(得分:1)

使用ToLookUp扩展方法而不是

var schoolCities = schoolsWithAddresses
.Where(school => school.Address.City != null)
.ToLookup(sc => sc.Address.City.Name.ToLower());

答案 2 :(得分:1)

我认为你想要的是Lookup

  

表示每个映射到一个或多个值的键集合。

使用示例:

Lookup<string, School> schoolCities = schoolsWithAddresses
    .Where(school => school.Address.City != null)
    .ToLookup(school => school.Address.City);

IEnumerable<School> schoolsInLondon = schoolCities["London"];

答案 3 :(得分:1)

这样的事情:

Dictionary<string, List<School>> schoolCities = schoolsWithAddresses
            .Where(school => school.Address.City != null)
            .GroupBy(school => school.Address.City)
            .ToDictionary(group => group.Key, group => group.ToList());

答案 4 :(得分:0)

试试这个

var schoolCities = schoolsWithAddresses
.GroupBy(x => x.city!=null)
.ToDictionary(x => x.Key, x => x.ToList());