如何比较两个列表并返回4个类别列表

时间:2018-10-17 11:15:49

标签: c# .net linq

我有两个具有相同属性的列表,我想比较它们之间的数据,我需要在视图中显示三个列表

  1. NewlyAdded员工(完成)
  2. Deleted员工(完成)
  3. Common员工(完成)
  4. 更新后的员工(不知道如何操作)

我已经列出了前3个列表,但是我不知道如何获取更新的数据,然后可以将更改部署到destEmps上,这样任何人都可以帮助我?

public class srsEmployee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string EmpCode { get; set; }
    public Nullable<decimal> Salary { get; set; }
    public Nullable<system.datetime> StartDate { get; set; }
    public Nullable<system.datetime> BOD { get; set; }
    public int DepartmentId { get; set; }
    public bool Active { get; set; }

    public virtual srsDepartment srsDepartment { get; set; }
}

public class destEmployee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string EmpCode { get; set; }
    public Nullable<decimal> Salary { get; set; }
    public Nullable<system.datetime> StartDate { get; set; }
    public Nullable<system.datetime> BOD { get; set; }
    public int DepartmentId { get; set; }
    public bool Active { get; set; }

    public virtual destDepartment destDepartment { get; set; }
}

这些是我用来获取3个列表的查询:

var Common = destEmps.Where(n => srsEmps.Any(o => o.EmpCode == n.EmpCode)).ToList();
var Deleted = srsEmps.Where(o => !destEmps.Any(n => n.EmpCode == o.EmpCode)).ToList();
var NewlyAdded = destEmps.Where(n => !srsEmps.Any(o => o.EmpCode == n.EmpCode)).ToList();

3 个答案:

答案 0 :(得分:1)

var Updated =
            from d in destEmps
            join c in srsEmployee
            on c.Id equals d.Id
            where d.Name != c.Name || d.EmpCode != c.EmpCode ..........
            select d;

 foreach(var element in destEmps)
        {
            var oldValue = srsEmployee.First(t => t.Id == element.Id);
            element.Name = oldValue.Name;
            .....
        }

答案 1 :(得分:0)

您可以创建一个方法来使用Employee类的所有属性生成哈希,然后具有相同ID但不同哈希的元素将被更新。

您可以使用此链接Generate hash of object consistently

中接受的答案来生成哈希

P.S。我认为您应该对“源”和“目标”列表使用相同的类。

答案 2 :(得分:0)

我建议您在Employee类中创建一个Equals方法,然后使用该方法进行比较

public bool Equals(Employee other)
{
    if (other == null)
    {
        return false;
    }
    else
    {
        // Do your equality test here.
        return (this.ID = other.ID &&
                this.Name = other.Name);
        // etc...
    }
}

然后您可以使用它在一个列表中查找所有项目,而另一个列表包含一个相等的项目。

相关问题