简体   繁体   中英

Selecting rows with distinct column values using LINQ

I have a generic list of SharePoint list items (List employees)

The SharePoint list contains the two columns, "Employee Name" and "Employee Designation"

I want to get an object List which contains distinct "Employee Designation" column values.

How do I do this using LINQ?

This didnt work for me:

 var designations = from SPListItem employee in employees
                    select new {Designation = employee["Employee Designation"].ToString().Distinct()};

If you are only retrieving the string value of that column, you can avoid writing an equality comparer by selecting a string (instead of an object containing a string property).

var designations = (from SPListItem employee in employees
                    select employee["Employee Designation"].ToString())
                   .Distinct()
                   .ToList();

You have to use the Distinct method on the sequence, and you will need to provide a custom implementation of IEqualityComparer<T> , because of this you will need an explicit class for the object you are creating.

var designations = (from SPListItem employee in employees
                   select new 
                   {
                     Designation = employee["Employee Designation"].ToString()
                   }).Distinct(comparer);

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