简体   繁体   中英

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

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

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