LINQ – 从嵌套列表中获取值的总数
我有一个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 phones { get; set; } public List categories { get; set; } }
我有一个包含Class
的Generic List
:
public List Companies = new List();
我想做两件事:
- 获得一个明确的类别列表
- 获得每个类别的公司总数
我想我成功了第一件事:
Companies.SelectMany(c => c.categories).Distinct()
请告诉我你是否觉得有什么不妥。
我尝试了第二步: Companies.SelectMany(c => c.categories).Where(c=>c == Category).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))
Companies .SelectMany(c => c.categories) .GroupBy(c => c) .Select(g => new { Cateogry = g.Key, Count = g.Count() });
如果您想要特定类别,那么您的查询已经是正确的。