C# LINQ-从嵌套列表中获取值的总计数
我有一门C# LINQ-从嵌套列表中获取值的总计数,c#,linq,C#,Linq,我有一门课: public class Company { public int id { get; set; } public string title { get; set; } public string address { get; set; } public string city { get; set; } public string zip { get; set; } public List<string> phones
课
:
public class Company
{
public int id { get; set; }
public string title { get; set; }
public string address { get; set; }
public string city { get; set; }
public string zip { get; set; }
public List<string> phones { get; set; }
public List<string> categories { get; set; }
}
上市公司
{
公共int id{get;set;}
公共字符串标题{get;set;}
公共字符串地址{get;set;}
公共字符串city{get;set;}
公共字符串zip{get;set;}
公共列表电话{get;set;}
公共列表类别{get;set;}
}
我有一个通用列表
,其中包含类
:
public class Company
{
public int id { get; set; }
public string title { get; set; }
public string address { get; set; }
public string city { get; set; }
public string zip { get; set; }
public List<string> phones { get; set; }
public List<string> categories { get; set; }
}
上市公司=新名单()代码>
我想做两件事:
获取类别的不同列表
获取每个类别的公司总数
我想我成功地做到了第一件事:
companys。选择many(c=>c.categories)。Distinct()
如果你觉得有什么问题,请告诉我
我尝试了第二步,如下所示:
companys。选择many(c=>c.categories)。其中(c=>c==categories)。Count()
但我不确定这是否真的正确
正确的
您需要将列表展平为(公司、类别)对,然后按类别分组:
from company in Companies
from category in company.Categories
group company by category into g
select new { Category = g.Key, Count = g.Count() }
编辑:如果你想知道一个给定类别中有多少家公司,你可以写
Companies.Count(c => c.Categories.Contains(categoryName))
如果您想将其用于特定类别,那么您的查询已经是正确的。一家公司可以有多个类别,这是我需要的计数,一个特定类别下有多少家公司。它仍然会给我与我在Hasan的评论中所写相同的结果。那么您犯了一个错误。请出示您的代码和数据。@Dementic我的答案给出了您想要的。试试看,因为我需要指定类别,我认为它不需要。@Dementic;如果您想对特定类别进行查询,您的第二个查询也是正确的。它似乎是正确的,因为从我的数据来看,有2109家公司,两个类别(根据上面的代码),每个类别包含(3/7)家公司,总共10家,这是不对的。@Dementic那么您可能在同一家公司中有重复的类别条目。在这种情况下,您需要执行以下操作:SelectMany(c=>c.categories.Distinct())