【发布时间】:2017-05-02 15:51:39
【问题描述】:
我有两个具有不同键值对的相同类型的列表, List1 具有“isPermanent = true”,List2 具有 false 值,并且 List1 有一个额外的键“nextVacationDate”。
我正在尝试将这些合并如下,但恐怕由于值不同,我仍然会得到重复项。我需要将两个列表合并到一个列表中,并首先按 List1 排序(永久员工优先)。有没有更好的方法使用 LINQ 来做到这一点?
public newList1 List1(string abcd)
{
var result = serviceMethod1(abcd);
var newList1 = new List<emp>();
if (result == null) return null;
newList.AddRange(
result.Select(x => new Model
{
firstName = x.FName,
secondName = x.SName,
address = x.Address,
employeeId = x.EmpId,
isPermanent = true,
nextVacationDate =x.VacDt,
salary = x.Bsalary
}));
return newList1;
}
public newList2 List2(string defg)
{
var result = serviceMethod2(defg);
var newList2 = new List<emp>();
if (result == null) return null;
newList.AddRange(
result.Select(x => new Model
{
firstName = x.FName,
secondName = x.SName,
address = x.Address,
employeeId = x.EmpId,
isPermanent = false,
salary = x.Bsalary
}));
return newList2;
}
private List<emp> EmployyeList(List<emp> newList1, List<emp> newList2)
{
var sortedEmpList1 = newList1.OrderBy(i => i.Fname);
var sortedEmpList2 = newList2.OrderBy(i => i.Fname);
List<MeterModel> combinedList = newList1.Union(newList2) as List<emp>;
return combinedList;
}
【问题讨论】:
-
如果这个标志对于平等真的不重要你可能想在你的
Model类上实现IEquatable<Model>然后使用newList1.Union(newList2) -
你说
List1有一个额外的密钥isPermanent但它没有——你是说nextVacationDate吗?另外,由于它们都是new Model(应该是new emp?),它不能是额外的键,只是List1具有键值。我想你想要的是 Linq 扩展方法.DistinctBy。然后你可以做.OrderBy(i => new { !i.isPermanent, i.Fname })。