我有Class
:
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; }
}
我有Generic List
,其中包含Class
:
public List<Company> Companies = new List<Company>();
我想做两件事:
我认为我成功了第一件事:
Companies.SelectMany(c => c.categories).Distinct()
如果您认为有任何问题,请告诉我。
我尝试了第二步:
Companies.SelectMany(c => c.categories).Where(c=>c == Category).Count()
但我不确定这是不对的。
答案 0 :(得分:5)
正确
您需要将列表展平为(公司,类别)对,然后按类别分组:
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))
答案 1 :(得分:3)
Companies
.SelectMany(c => c.categories)
.GroupBy(c => c)
.Select(g => new
{
Cateogry = g.Key,
Count = g.Count()
});
如果您想要特定类别,那么您的查询已经正确。