Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ的GroupBy和Count_C#_Linq_Group By_Count - Fatal编程技术网

C# 使用LINQ的GroupBy和Count

C# 使用LINQ的GroupBy和Count,c#,linq,group-by,count,C#,Linq,Group By,Count,我有一个名为Component的类,它具有以下属性: public class Component { public string VerticalType {get; set;} public string ProductCode {get; set;} } 我有一个列表: public List<Component> ComponentList; 我有一本字典,我想用VerticalType作为键,Count作为值来填充它。所以我的字典应该是这样的: (Int

我有一个名为Component的类,它具有以下属性:

public class Component
{
    public string VerticalType {get; set;}
    public string ProductCode {get; set;}
}
我有一个列表

public List<Component> ComponentList;
我有一本字典,我想用VerticalType作为键,Count作为值来填充它。所以我的字典应该是这样的:

(Internet,2)
(TV,1)
(Video,1)
我正在尝试类似的东西,但不知道如何获得计数

var results = lead.SelectedOffer.ComponentList.GroupBy(
     p => p.VerticalType,
     p => p.VerticalTypeCount,
     (key, g) => new { VerticalType = key, Count =  });

要获取组中的计数,请使用
count()
方法:

Count = g.Count()
另一方面,由于您只需要从
VerticalType
映射到计数,因此我建议您:

lead.SelectedOffer.ComponentList.GroupBy(p => p.VerticalType)
                  .ToDictionary(g => g.Key, g => g.Count());
或者,如果您希望持久使用匿名类型的IEnumerable,那么您仍然不需要在示例代码中使用特定的
GroupBy
重载,而是需要以下重载:

lead.SelectedOffer.ComponentList.GroupBy(p => p.VerticalType)
                  .Select(g => new { VerticalType = g.Key, Count = g.Count() });

完美的我同意第一个建议,还有一件事。当我将其分配给类型为
dictionary
@HumaAli yes的dictionary时,我得到了转换错误,这是因为生成的类型是
dictionary
,其中
string
VerticalType
,而
int
是相应的计数。啊,找到了。谢谢
lead.SelectedOffer.ComponentList.GroupBy(p => p.VerticalType)
                  .Select(g => new { VerticalType = g.Key, Count = g.Count() });