C#两个列表之间的差异

时间:2014-01-09 12:12:21

标签: c#

美好的一天。我正在浏览论坛,但没有找到任何有用的东西。

我有两个自定义列表,我需要显示差异的第三个列表。

list1[0].Id = 10;
list1[0].Name = "Peter";
list1[0].Age = 45;
list1[0].Group = "Group1";

list1[1].Id = 11;
list1[1].Name = "John";
list1[1].Age = 42;
list1[1].Group = "Group2";

list1[2].Id = 12;
list1[2].Name = "Mike";
list1[2].Age = 32;
list1[2].Group = "Group2";


list2[0].Id = 10;
list2[0].Name = "Peter";
list2[0].Age = 45;
list2[0].Group = "Group2";

list2[1].Id = 11;
list2[1].Name = "John";
list2[1].Age = 48;
list2[1].Group = "Group2";

list2[2].Id = 12;
list2[2].Name = "Mike";
list2[2].Age = 32;
list2[2].Group = "Group2";

我需要生成列表3,其中包含id为10和id为11的差异记录

3 个答案:

答案 0 :(得分:1)

在答案失控之前,让我发一个特定于这个问题的答案,但方法取自:

https://stackoverflow.com/a/5636486/103139

创建以下两个类

public class Person{
    public int ID{ get; set;}
    public int Age{ get; set;}
    public string Name{ get; set;}
    public string Group{ get; set;}

    // constructors and other class specific 
    // methods come here.
}

public class PersonComparer : IEqualityComparer<Person>
{
    public int GetHashCode(Person p)
    {
        if (p == null)
        {
            return 0;
        }

        // you can put any custom hashcode generation here.
        return p.Name.GetHashCode() 
                    ^ p.Age.GetHashCode 
                    ^ p.Group.GetHashCode();

    }

    public bool Equals(Person p1, Person p1) {
        if (object.ReferenceEquals(p1, p2)) {
            return true;
        }
        if (
            object.ReferenceEquals(p1, null) ||
            object.ReferenceEquals(p2, null)
        ) {
            return false;
        }
        return p1.Name == p2.Name &&
                p1.Age == p2.Age &&
                p1.Group == p2.Group;   // consider equal ordinal ignore case
    }
}

在你的名单所在的地方做了以下几点:

var diff = list1.Except(list2, new PersonComparer()).ToList();

鉴于您的列表是List。请注意,这不包括支票中的ID,因为我从您的OP示例中获取。

答案 1 :(得分:-2)

var diff1 = list1.Where(p =&gt; list2.FirstOrDefault(q =&gt;(p.Age == q.Age&amp;&amp; p.Group == q.Group&amp;&amp; p.Id == q.Id&amp;&amp; p.Name == q.Name))== null)。ToList();

        var diff2=list2.Where(p => list1.FirstOrDefault(q => (p.Age == q.Age && p.Group == q.Group && p.Id == q.Id && p.Name == q.Name)) == null).ToList();

        var diff = diff1.Concat(diff1).ToList();

答案 2 :(得分:-2)

使用具有属性ID,年龄,名称和组的类

例如:class example {

                int Id;
                int age;
                string name;
                string group;

              }

创建班级列表

列表&lt; example&gt; list1 = new List&lt; example&gt;();

list1.Add(新示例{Id = 1,age = 22,name =“n1”,group =“g1”});

list1.Add(新示例{Id = 2,age = 30,name =“n2”,group =“g2”});

获得差异的第3个清单

list1.Add(新示例{Id = list1 [0] .Id-list [1] .Id,age = list1 [0] .age-list [1] .age});

现在你的

list1 [2]包含liss1 [0],list [1]

之间的差异