查找Linq Query在不同地区的公司数量

时间:2016-08-31 19:07:24

标签: linq

如何构建linq查询以查找不同地区的公司数量。

Region Class
-------------
int Id
string Name

Company Class
-------------
int Id
string Name
int RegionId

i.e 
Asia = 100,
Middle East = 200,
.. etc

1 个答案:

答案 0 :(得分:1)

You need to use the LINQ GroupBy method ( https://msdn.microsoft.com/en-us/library/bb534304(v=vs.110).aspx ).

Assuming you have a relationship between Regions and Companies, and that region names are unique, you could use something like the following (or read the docs to learn how else to use the Group By data):

Companies
.GroupBy(c => c.Region.Name)
.Select(g => new { 
       Region = g.Key, 
       CompanyCount = g.Count()
});