Arianule
Arianule

Reputation: 9043

Retrieving distinct objects in a list based on a property values

Apologies,

Struggling a bit to get my head around this.

I need to get the distinct values in the following list based on a property value of 'Answer' and the property value of EmployeeNumber

I retrieved values from a database

EmployeeNumber     Answer
1234         a
1234         a
1234         c

9986         a
9986         a
9986         a

9987         b
9987         b
9987         a

the result of my list should be like this

EmployeeNumber     Answer
1234         a
1234         c

9986         a

9987         b
9987         a

How can I achieve this?

I started with the following var list1 = usersDevicesused.DistinctBy(x => x.Answer).ToList(); which then only brings back 3 values which is not what I am after.

Kind regards

Upvotes: 0

Views: 29

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460028

You want to group by EmployeeNumber + Answer and then take the first of each group:

var list1 = usersDevicesused
    .GroupBy(x => new { x.EmployeeNumber, x.Answer })
    .Select(grp => grp.First())
    .ToList();

Upvotes: 2

Related Questions