简体   繁体   English

Linq:按一列分组但必须与另一列不同

[英]Linq: Group by one column but must distinct other column

In my linq query I want to query the service table which has a visitId and a deviceId.在我的 linq 查询中,我想查询具有 visitId 和 deviceId 的服务表。 I want to be able to group by the visit but have the deviceId distinct.我希望能够按访问进行分组,但具有不同的 deviceId。 Currently with my setup I can group by visitId but I'm having trouble showing disitnct devices in the result when the visit is the same.目前,通过我的设置,我可以按访问 ID 分组,但是当访问相同时,我无法在结果中显示不同的设备。

from s in db.Services.Where(condition)
                 where s.Active && (hasSupportGeneralAccess || s.Visit.Site.Branch.Users.Any(u => u.Id == userId)) && s.Device != null
                 orderby s.Visit.Start descending
                 group s by s.Visit into newgroup
                 select newgroup.FirstOrDefault()

Any Help is greatly appreciated!任何帮助是极大的赞赏!

After you have grouped by Visit, all your entities (I'm guessing a Service given that it comes from a collection called Services) are in a collection associated with a given visit.按访问分组后,您的所有实体(我猜是一个服务,因为它来自名为服务的集合)都在与给定访问关联的集合中。 If you want to know the distinct devices in that list you can ask for them:如果您想知道该列表中的不同设备,您可以询问它们:

select newgroup.Select(x => x.Device).Distinct()

newgroup is like a List<Service> , and one of the properties of a Service is Device. newgroup 就像一个List<Service>List<Service>的属性之一是 Device。 If I'd handed you a List<Service> and asked for all the distinct Device in it, you'd Select the Device out of the list and then ask for Distinct.. this is no different except that instead of one List<Service> you've got one list per unique Visit - if there are 10 Visits then there are 10 List<Service> you need to process如果我给你一个List<Service>并要求其中的所有不同设备,你会从列表中选择设备,然后要求 Distinct .. 这没有什么不同,除了一个List<Service>每次唯一访问都有一个列表 - 如果有 10 次访问,则需要处理 10 个List<Service>

In this case, we can group the combination of both visit and device like below so that we get repeated device for the same visit.在这种情况下,我们可以像下面这样对访问和设备的组合进行分组,以便我们获得相同访问的重复设备。

from s in db.Services.Where(condition)
where s.Active && (hasSupportGeneralAccess ||  s.Visit.Site.Branch.Users.Any(u => u.Id == userId)) && s.Device != null orderby s.Visit.Start descending
group s by (s.Visit + "." + s.Device) into newgroup
select newgroup.FirstOrDefault();

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

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