简体   繁体   English

使用LINQ选择具有不同列值的行

[英]Selecting rows with distinct column values using LINQ

I have a generic list of SharePoint list items (List employees) 我有一个SharePoint列表项的通用列表(列出员工)

The SharePoint list contains the two columns, "Employee Name" and "Employee Designation" SharePoint列表包含两列,“员工姓名”和“员工指定”

I want to get an object List which contains distinct "Employee Designation" column values. 我想获得一个包含不同“Employee Designation”列值的对象List。

How do I do this using LINQ? 如何使用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. 您必须在序列上使用Distinct方法,并且您需要提供IEqualityComparer<T>的自定义实现,因此您需要为要创建的对象提供显式类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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