HELP_ME
HELP_ME

Reputation: 2729

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.

Upvotes: 0

Views: 2652

Answers (2)

david.s
david.s

Reputation: 11403

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

Upvotes: 3

Tigran
Tigran

Reputation: 62248

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.

Upvotes: 1

Related Questions