简体   繁体   English

LINQ to实体C#分组依据/不同查询

[英]linq to entities C# Group By / Distinct query

I have a Linq to Entity query that pulls out photos of my database. 我有一个Linq to Entity查询,可提取数据库中的照片。 My ultimate goal is just to get the size and sum them up but I need to do a distinct call on the ID first because I am grouping the call and obviously there could be multiple records with the same photo size so I cant call distinct on that. 我的最终目标是获取尺寸并进行汇总,但是我首先需要对ID进行不同的调用,因为我正在对调用进行分组,并且显然可能有多个具有相同照片尺寸的记录,因此我无法对此进行不同的调用。 So how would I call a distinct on the photoID but pull the photo size? 那么,如何在photoID上调用非重复性,但又缩小照片尺寸呢? thanks for any help. 谢谢你的帮助。

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)

You can use GroupBy and the select the first item in that group to get the effect of a DistinctBy . 您可以使用GroupBy并选择该组中的第一项来获得DistinctBy的效果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM