问题描述
我有一个类
:
公共类公司
{
公众诠释ID {搞定;组; }
公共字符串的标题{搞定;组; }
公共字符串的地址{搞定;组; }
公共字符串城市{搞定;组; }
公共字符串拉链{搞定;组; }
公开名单<串GT;电话{搞定;组; }
公开名单<串GT;类别{搞定;组; }
}
和我有一个泛型列表
其中包含类
:
公开名单<公司>公司=新的List<公司>();
我想要做的两件事情:
- 获得类别的不同列表
- 得到每类企业的总数
我想我管理的第一件事:
Companies.SelectMany(C =以及c .categories).Distinct()
请告诉我,如果你认为有什么不妥。
我想第二个步骤像这样:
Companies.SelectMany(C => c.categories)。凡(C =以及c ==类别).Count之间的()
,但林不知道这是很合适。
-
正确
-
您需要拼合列表进入(公司类别)对,然后按类别组:
从公司公司
从类别中company.Categories
组公司类别为G
选择新{类别= g.Key,计数= g.Count ()}
修改:如果你想找出多少企业是在一个给定的类别,你可以写
Companies.Count(三= GT; c.Categories.Contains(类别名))
i have a 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; }
}
and i have a Generic List
which contains that Class
:
public List<Company> Companies = new List<Company>();
i want to do two things:
- get a distinct list of the categories
- get a total count of companies per category
i think i managed to the the first thing:
Companies.SelectMany(c => c.categories).Distinct()
please tell me if you think anything is wrong with that.
i tried the second step as so:Companies.SelectMany(c => c.categories).Where(c=>c == Category).Count()
but im not sure that is really right.
Correct
You need to flatten the list into (company, category) pairs, then group by category:
from company in Companies from category in company.Categories group company by category into g select new { Category = g.Key, Count = g.Count() }
EDIT: If you want to find out how many companies are in a single given category, you can write
Companies.Count(c => c.Categories.Contains(categoryName))
这篇关于LINQ - 得到嵌套列表值的总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!