LINQ按多个属性分组并创建字典

时间:2019-02-05 08:25:29

标签: c# linq format key

我有一个名为ScrewBoltPattern的类的对象列表。

我想创建一个字典,其中包含ScrewBoltPattern每个系列的出现次数。为了确定螺钉是否属于一个家族,我使用该类的一些属性。

为简化此查询,假设我使用“长度”和“直径”属性。

我想创建一个字典,该字典的键格式如screw.Length +“ _” + screw.Diameter

我怎么能得到这个?

这是我到目前为止所做的

Dictionary<string, int> boltFamilyList = selectedBolts
                .GroupBy(bolt => new { bolt.Length, bolt.Diameter })
                .ToDictionary(bolt => bolt.Key, bolt => bolt.Count());

我需要在某处给字典键指定格式,但是我不知道该怎么做。

4 个答案:

答案 0 :(得分:5)

您可以通过以下方式格式化组中的密钥:

Dictionary<string, int> boltFamilyList = selectedBolts
    .GroupBy(bolt => $"{bolt.Length}_{bolt.Diameter}")
    .ToDictionary(bolt => bolt.Key, bolt => bolt.Count());

您的组密钥(以及代理的字典密钥)将是该格式化的字符串。

Try it online

答案 1 :(得分:4)

您也可以使用ILookup来实现相同的目标:

ILookup<string, int> lookup = 
    selectedBolts.ToLookup(bolt => $"{bolt.Length}_{bolt.Diameter}");

然后

int count = lookup["12_36"].Count();

答案 2 :(得分:1)

尽管您已经有了解决方案,但只想指出解决方案,因为您真的很接近解决方案...

Dictionary<string, int> boltFamilyList = selectedBolts
    .GroupBy(bolt => new { bolt.Length, bolt.Diameter })
    .ToDictionary(bolt => bolt.Key, bolt => bolt.Count());

在列表行中,您可以创建密钥:

.ToDictionary(bolt => $"{bolt.Key.Length}_{bolt.Key.Diameter}", bolt => bolt.Count());

如果查看Enumerable.ToDictionary方法的签名,您会看到第一个参数是Func<TSource,TKey> keySelector,在您的情况下,TSource是匿名类型,而TKey是字符串。您所需要做的就是定义TSourceTKey之间的映射,而这正是功能bolt => $"{bolt.Key.Length}_{bolt.Key.Diameter}"的作用。

答案 3 :(得分:0)

您可能也不知道此解决方案,您可能根本不需要字符串格式。 (您可以将C#7与值元组一起使用)

Dictionary<(int length, int diameter), int> boltFamilyList = selectedBolts
    .GroupBy(bolt => (bolt.Length, bolt.Diameter))
    .ToDictionary(bolt => bolt.Key, bolt => bolt.Count());

访问方式

dic.TryGetValue((10, 20), out int count);

长度和直径分别为10和20