LINQ组由多个属性和创建字典

问题描述 投票:3回答:4

我从一个类叫做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());

我需要给格式字典关键的地方,但我不知道该怎么做。

c# linq format key
4个回答
5
投票

您可以格式化组通过在关键:

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

您的组密钥(和代理您的字典键)将是格式化字符串。

Try it online


4
投票

你也可以使用一个ILookup来达到同样的目的:

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

接着

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

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}"做什么。


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是长度和直径

© www.soinside.com 2019 - 2024. All rights reserved.