使用LINQ计数的UNIQUE列

时间:2015-11-05 12:12:02

标签: c# entity-framework linq linq-to-entities

我有一个包含以下列的表

Id
Address
City
Date
maxSeat
StateId [Foreign key with table State with columns Id,Name] 

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

例如

  

State1 5行

     

State2 3行

     

State3 1行

     

State4 5行

List<int> uniqStates = dbContext.conflocations.Select(item => item.StateId)
                                              .Distinct().ToList();

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

3 个答案:

答案 0 :(得分:6)

您需要GroupBy: -

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

答案 1 :(得分:2)

您可以使用GroupBy方法执行此操作:

var uniqStates = dbContext.conflocations.GroupBy(item => item.StateId).Select(g=>new {StateId=g.Key,Count=g.Count()}).ToList();

或者使用查询语法,您也可以这样做:

 var uniqStates= from conf in dbContext.conflocations
                 group conf by conf.StateId into g
                 select new {StateId=g.Key,
                             Count=g.Count()
                            }; 

现在要获取州名称,如果您的State实体中有Conflocation类型的导航属性,那么您可以执行以下操作:

var uniqStates= from conf in dbContext.conflocations
                 group conf by conf.StateId into g
                 select new {StateId=g.Key,
                             Name=g.FirstOrDefault().State.Name
                             Count=g.Count()
                            }; 

更新

如果您的StateWiseVenues类具有与此查询投影结果的匿名类型相同的属性类型,则可以执行以下操作:

var uniqStates= from conf in dbContext.conflocations
                group conf by conf.StateId into g
                select new StateWiseVenues {StateId=g.Key,
                                            Name=g.FirstOrDefault().State.Name
                                            Count=g.Count()
                                           }; 
 if(uniqStates !=null) 
 { 
   state_venues = uniqStates.ToList();
 } 

答案 2 :(得分:1)

你需要jint这两个表:

using( var dbContext=...)
{
   var results = from c in dbContext.conflocations
                 from s in dbContext.States.Where(x=>x.Id = c.StateId).DefaultIfEmpty()
                 group new {c, s} by s.StateId into grp
                 select new { 
                              StateId = grp.Key,
                              StateName= grp.Max(x=>x.s.Name),
                              Count = grp.Count()
                            };
   ...
}