我有一个Employee的集合
Class Employee
{
empName
empID
empLoc
empPL
empShift
}
Run Code Online (Sandbox Code Playgroud)
我的清单包含
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
Run Code Online (Sandbox Code Playgroud)
我需要让员工拥有不同的值empLoc,empPL,empShift.
有没有办法用LINQ实现这个目标?
Tim*_*ter 38
您可以实现自定义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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以使用这个重载Enumerable.Distinct:
var distinct = employees.Distinct(new Employee.Comparer());
Run Code Online (Sandbox Code Playgroud)
使用匿名类型的可重用性较低,功能强大且效率较低的方法:
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();
Run Code Online (Sandbox Code Playgroud)
cuo*_*gle 35
您可以使用GroupBy与匿名类型,然后得到First:
list.GroupBy(e => new {
empLoc = e.empLoc,
empPL = e.empPL,
empShift = e.empShift
})
.Select(g => g.First());
Run Code Online (Sandbox Code Playgroud)
Agh*_*oub 11
您可以尝试使用此代码
var result = (from item in List
select new
{
EmpLoc = item.empLoc,
EmpPL= item.empPL,
EmpShift= item.empShift
})
.ToList()
.Distinct();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148376 次 |
| 最近记录: |