简体   繁体   中英

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

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.

You can order users by week, then group them by Id and select the first user in each group:

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()

Distinct can be used also with IEqualityComparer , like

IEnumerable<User> users =  users.Distinct(new UserComparer());

where UserComparer a class that implements some custom comparison logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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