【问题标题】:Merge two Lists of same type with diff values and avoid duplicates合并两个具有不同值的相同类型的列表并避免重复
【发布时间】: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&lt;Model&gt;然后使用newList1.Union(newList2)
  • 你说List1 有一个额外的密钥isPermanent 但它没有——你是说nextVacationDate 吗?另外,由于它们都是new Model(应该是new emp?),它不能是额外的键,只是List1 具有键值。我想你想要的是 Linq 扩展方法.DistinctBy。然后你可以做.OrderBy(i =&gt; new { !i.isPermanent, i.Fname })

标签: c# .net list linq c#-4.0


【解决方案1】:

您可以过滤第二个列表以避免重复:

newList1.Union(newList2.Where(emp2 => !newList1.Any(emp1 => emp1.employeeId == emp2.employeeId)))

【讨论】:

    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多