我从一个类叫做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());
我需要给格式字典关键的地方,但我不知道该怎么做。
您可以格式化组通过在关键:
Dictionary<string, int> boltFamilyList = selectedBolts
.GroupBy(bolt => $"{bolt.Length}_{bolt.Diameter}")
.ToDictionary(bolt => bolt.Key, bolt => bolt.Count());
您的组密钥(和代理您的字典键)将是格式化字符串。
你也可以使用一个ILookup来达到同样的目的:
ILookup<string, int> lookup =
selectedBolts.ToLookup(bolt => $"{bolt.Length}_{bolt.Diameter}");
接着
int count = lookup["12_36"].Count();
虽然你已经有解决方案,只是想指出你是如何解决的,因为你是真正贴近的解决方案...
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
是字符串。所有你需要做的就是定义TSource
和TKey
之间的映射,这是功能bolt => $"{bolt.Key.Length}_{bolt.Key.Diameter}"
做什么。
你可能不知道这个解决方案,以及,你可能不需要在字符串的所有格式。 (你可以使用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是长度和直径