linq to entities C#Group By / Distinct query

时间:2013-07-10 14:48:53

标签: c# linq linq-to-entities

我有一个Linq to Entity查询,可以提取我数据库的照片。我的最终目标只是获得大小并总结它们,但我需要首先对ID进行明确的调用,因为我正在对呼叫进行分组,显然可能有多个具有相同照片大小的记录,因此我无法对其进行区分。那么我如何在photoID上调用一个独特的但是拉出照片大小?谢谢你的帮助。

from x in _context.Clients
join media in _context.Mediae 
on x.ID equals media.ClientID into Medias
from submedia in Medias.DefaultIfEmpty()
group new { x.ClientName, submedia } by new { x.ClientName } into g

//I would like to get the Sum of the MediaSize out of this But I call distinct on ID                       
let mediaCount = g.Where(x=>x.submedia  != null).Select(x=>x.submedia .ID).Distinct()
//Example of what I wish would work below
//g.Where(x => x.subEventMedia != null).Select(x => x.subEventMedia.ID).Distinct().Sum(x => x.subEventMedia.MediaSize)

1 个答案:

答案 0 :(得分:1)

您可以使用GroupBy并选择该组中的第一项来获得DistinctBy的效果。

let mediaCount = g.Where(x=>x.submedia != null)
    .GroupBy(x=>x.submedia.ID)
    .Sum(mediaGroup => mediaGroup.FirstOrDefault().submedia.MediaSize)