简体   繁体   English

如何将LINQ查询分组到字典<string, string>

[英]How to group LINQ query to dictionary<string, string>

I have a simple model that I'm trying to group: 我有一个简单的模型,我正在尝试分组:

public class PracticeArea
{
    [Key]
    public int PracticeAreaID { get; set; }

    public string Name { get; set; }

    public string Type { get; set; }

}

I'd like to group by Type, how can I convert this: 我想按类型分组,我该怎么转换它:

var practiceAreas = (from c in db.PracticeAreas
                             select c).

to: 至:

public Dictionary<string, string> groupedPracticeAreas { get; set; }

I'm not sure how grouping works within Linq - I can run .ToGroup(),. 我不确定Linq中的分组是如何工作的 - 我可以运行.ToGroup(),. but that doesn't give me my dictionary. 但那并没有给我我的字典。

I've tried: 我试过了:

practiceAreas = practiceAreas.ToDictionary(x => x.Type, x => x.Name);

But that gave me a cast error 但这给了我一个演员错误

This should not throw cast exception if both type and name are strings: 如果类型和名称都是字符串,则不应抛出cast异常:

practiceAreas.ToDictionary(x => x.Type, x => x.Name)

But this would throw if there is more than one practice area exist for some type. 但是如果某种类型存在多个练习区域,则会抛出。 You can use one of following options: 您可以使用以下选项之一:

1) Use lookup instead of dictionary. 1)使用查找而不是字典。 It will create lookup for names by area type 它将按区域类型创建名称查找

practiceAreas.ToLookup(pa => pa.Type, pa => pa.Name)

2) Use dictionary with collection to hold all names for each type, eg Dictionary<string, List<string>> : 2)使用带有集合的字典来保存每种类型的所有名称,例如Dictionary<string, List<string>>

practiceAreas.GroupBy(pa => pa.Type)
             .ToDictionary(g => g.Key, g => g.Select(pa => pa.Name).ToList())

3) Join all names in single string 3)将所有名称加入单个字符串中

practiceAreas.GroupBy(pa => pa.Type)
         .ToDictionary(g => g.Key, g => String.Join("," g.Select(pa => pa.Name)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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