我有一个名为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());
我需要在某处给字典键指定格式,但是我不知道该怎么做。
答案 0 :(得分:5)
您可以通过以下方式格式化组中的密钥:
Dictionary<string, int> boltFamilyList = selectedBolts
.GroupBy(bolt => $"{bolt.Length}_{bolt.Diameter}")
.ToDictionary(bolt => bolt.Key, bolt => bolt.Count());
您的组密钥(以及代理的字典密钥)将是该格式化的字符串。
答案 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
是字符串。您所需要做的就是定义TSource
和TKey
之间的映射,而这正是功能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