从C#中使用LINQ列表中选择不同的值 [英] Select distinct values from a list using LINQ in C#
本文介绍了从C#中使用LINQ列表中选择不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有员工的集合
Class Employee
{
empName
empID
empLoc
empPL
empShift
}
我的列表中包含
My list contains
empName,empID,empLoc,empPL,empShift
E1,1,L1,EPL1,S1
E2,2,L2,EPL2,S2
E3,3,L3,EPL3,S3
E4,4,L1,EPL1,S1
E5,5,L5,EPL5,S5
E6,6,L2,EPL2,S2
我需要有不同的价值观的员工 empLoc,empPL,empShift。
I need to take the employees having distinct values empLoc,empPL,empShift.
有没有什么办法来实现这一目标使用LINQ?
Is there is any way to achieve this using LINQ ?
推荐答案
您可以实现自定义的<一个href="http://msdn.microsoft.com/en-us/library/ms132151.aspx"><$c$c>IEqualityComparer<Employee>$c$c>:
You could implement a custom IEqualityComparer<Employee>
:
public class Employee
{
public string empName { get; set; }
public string empID { get; set; }
public string empLoc { get; set; }
public string empPL { get; set; }
public string empShift { get; set; }
public class Comparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
return x.empLoc == y.empLoc
&& x.empPL == y.empPL
&& x.empShift == y.empShift;
}
public int GetHashCode(Employee obj)
{
unchecked // overflow is fine
{
int hash = 17;
hash = hash * 23 + (obj.empLoc ?? "").GetHashCode();
hash = hash * 23 + (obj.empPL ?? "").GetHashCode();
hash = hash * 23 + (obj.empShift ?? "").GetHashCode();
return hash;
}
}
}
}
现在你可以使用这个超负荷的<一个href="http://msdn.microsoft.com/en-us/library/bb338049.aspx"><$c$c>Enumerable.Distinct$c$c>:
Now you can use this overload of Enumerable.Distinct
:
var distinct = employees.Distinct(new Employee.Comparer());
少可重复使用,强大和有效的方法,使用匿名类型:
The less reusable, robust and efficient approach, using an anonymous type:
var distinctKeys = employees.Select(e => new { e.empLoc, e.empPL, e.empShift })
.Distinct();
var joined = from e in employees
join d in distinctKeys
on new { e.empLoc, e.empPL, e.empShift } equals d
select e;
// if you want to replace the original collection
employees = joined.ToList();
这篇关于从C#中使用LINQ列表中选择不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文