Skip to content

linq to entity GroupBy多个字段

L edited this page May 16, 2022 · 5 revisions

代码段1

var items = _voteRecordRepository.GetAll()
            .Where(x => programIds.Contains(x.ProgrammeId))
            .GroupBy(x=>new {x.ClientType,x.ProgrammeId})
            .Select((group)=>new ProgramVoteRecordSelectItem()
            {
                ProgramId = group.Key.ProgrammeId,
                GetVote=group.Count(),
                ClientType=group.Key.ClientType,
                //这里group是一个集合,如果要取某条记录的信息需要先查找实体,比如:
                DishName=group.FirstOrDefault()!=null?group.FirstOrDefault().DishName:"",
                NameList= group.ToList().Select(x=>x.Name).ToList(),
            })
            .ToList();

IGrouping<TKey, TElement>资料

https://msdn.microsoft.com/zh-cn/library/windows/apps/bb343251(v=vs.95).aspx

代码段2

from a in AQueryable
join b in BQueryable on a.BID equals b.ID
where queryCondition == null ||
        (
            ...
        )
let groupData = new { a, Count = b.Sum(item => item.Count)}
orderby a.ID descending
group groupData by new
{
    groupData.a.Field1,
    groupData.a.Field2,
    groupData.Count,
} into groupDatas
where groupDatas.Sum(item => item.Count) > 0
select new XXXClass
{
    ...
};
Clone this wiki locally