C#列表合并而不重复

时间:2011-07-15 11:08:14

标签: c# list merge

我的问题是在评论中的以下代码的末尾:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
class MyObj
{
    int m_id;

    public MyObj(int id)
    {
        this.m_id = id;
    }

    public int GetId()
    {
        return this.m_id;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var m0 = new MyObj(0);
        var m1 = new MyObj(1);
        var m2 = new MyObj(2);
        var m3 = new MyObj(3);
        var m4 = new MyObj(4);


        List<MyObj> refList1 = new List<MyObj>()
            {
                m0, m1, m2, m3
            };

        List<MyObj> refList2 = new List<MyObj>()
            {
                m1, m2, m3, m4
            };


        //How to merge refList2 into refList1 without id repeating,
        //so refList1 must be [m0, m1, m2, m3, m4]
    }
}
}

4 个答案:

答案 0 :(得分:3)

您可以使用LINQ执行此操作:

var resultList = refList1.Union(refList2).ToList();

但是,这需要MyObj实现IEquatable<MyObj>,或者使用Union的其他重载来获取IEqualityComparer<T>参数。

第一个解决方案需要进行此更改:

class MyObj : IEquatable<MyObj>
{
    int m_id;

    public MyObj(int id)
    {
        this.m_id = id;
    }

    public int GetId()
    {
        return this.m_id;
    }

    public bool Equals(MyObj other)
    {
        if (ReferenceEquals(null, other)) {
            return false;
        }
        if (ReferenceEquals(this, other)) {
            return true;
        }
        return other.m_id == this.m_id;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) {
            return false;
        }
        if (ReferenceEquals(this, obj)) {
            return true;
        }
        if (obj.GetType() != typeof(MyObj)) {
            return false;
        }
        return Equals((MyObj)obj);
    }

    public override int GetHashCode()
    {
        return this.m_id;
    }
}

第二种解决方案如下:

class MyComparer : IEqualityComparer<MyObj>
{
    public bool Equals(MyObj x, MyObj y)
    {
        return x.GetId() == y.GetId();
    }

    public int GetHashCode(MyObj obj)
    {
        return obj.GetId();
    }
}

var resultList = refList1.Union(refList2, new MyComparer()).ToList();

并且不需要更改class MyObj

答案 1 :(得分:1)

您可以使用Union

看看here

答案 2 :(得分:1)

使用Union Extension method

var merged = refList2.Union(refList1).ToList();

定义Equals / Hashcode方法。执行此操作后,它将自动删除重复项。

class MyObj{
     /*your stuff*/

     public override bool Equals(object obj)
     {        
        var r_list= obj as MyObj;
        if(r_list == null) return false;
        return this._m_id==r_list.m_id;
     }

     public override int GetHashCode()
     {
        return m_id;
     }
}

答案 3 :(得分:0)

refList1 = refList1.Union(refList2).Distinct.ToList();