[英]Selecting Distinct Rows Using Linq
I am currently returning a list using the following 我目前正在使用以下方法返回列表
Test.GetPrevList(Current.Id, UserId);
This list has 5 columns User ID
First Name
Last Name
Department
Week
此列表有5列
User ID
First Name
Last Name
Department
Week
What I noticed is that if an employee switched departments they will show up twice on the list. 我注意到的是,如果某个员工调换了部门,他们将在列表中出现两次。
What I want to do is select the most recent record based on the most recent week column, using Linq as the stored procedure is used multiple times. 我想做的是根据最近一周的列选择最新记录,使用Linq,因为存储过程被多次使用。
You can order users by week, then group them by Id and select the first user in each group: 您可以按周对用户排序,然后按ID对用户进行分组,然后在每个组中选择第一个用户:
var userList = Test.GetPrevList(Current.Id, UserId);
var users = userList.OrderByDescending(x => x.Week)
.GroupBy(x => x.UserId)
.Select(x => x.First());
use a simple LINQ call too Distinct()
也使用简单的LINQ调用
Distinct()
Distinct can be used also with IEqualityComparer
, like 区别也可以与
IEqualityComparer
一起使用,例如
IEnumerable<User> users = users.Distinct(new UserComparer());
where UserComparer
a class that implements some custom comparison logic. 其中
UserComparer
是实现一些自定义比较逻辑的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.