使用LINQ计数的UNIQUE列

Jib*_*hew 4 c# linq linq-to-entities entity-framework

我有一个包含以下列的表

Id
Address
City
Date
maxSeat
StateId [Foreign key with table State with columns Id,Name] 
Run Code Online (Sandbox Code Playgroud)

我想写一个LINQ查询来获取唯一StateId的List及其计数

例如

State1 5行

State2 3行

State3 1行

State4 5行

List<int> uniqStates = dbContext.conflocations.Select(item => item.StateId)
                                              .Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

这将仅返回stateId的唯一列表.如何使用LINQ获取关联计数以及状态名称?

Rah*_*ngh 6

你需要GroupBy: -

var uniqStates = dbContext.conflocations.GroupBy(item => item.StateId)
                          .Select(x => new 
                                  {
                                      StateId = x.Key,
                                      Count = x.Count()
                                  });
Run Code Online (Sandbox Code Playgroud)