0

我有一个清单如下:

 public class MyClass
 {
    public int val1;
    public long val2;
    public string val3;
 }
class Program
{
    static void Main(string[] args)
    {
        List<MyClass> lstData=new List<MyClass>
        {
            new MyClass{val1=1,val2=2,val3="AA"},
            new MyClass{val1=1,val2=2,val3="BB"},
            new MyClass{val1=3,val2=4,val3="AA"},
            new MyClass{val1=3,val2=4,val3="BB"},
            new MyClass{val1=1,val2=2,val3="BB"},
            new MyClass{val1=3,val2=4,val3="AA"},

        };
    }
}

我想从列表中获取唯一行。在上面的示例中,以下列表是重复的

{val1=1,val2=2,val3="BB"}
 {val1=3,val2=4,val3="AA"}

我想消除重复的行并将不同的行从列表中取出。我怎么能这样做?

4

3 回答 3

3
var result = lstData.GroupBy(x=>new {x.val1, x.val2, x.val3}, (x,y)=>y.First())
                    .ToList();                        
于 2013-08-31T09:33:09.680 回答
2

您必须在您的类上实现GetHashCodeEquals方法MyClass,或者定义实现的自定义类IEqualityComparer<MyClass>

public class MyClassEqualityComparer : IEqualityComparer<MyClass>
{
    private static Lazy<MyClassEqualityComparer> _instance = new Lazy<MyClassEqualityComparer>(() => new MyClassEqualityComparer());

    public static MyClassEqualityComparer Instance
    {
        get { return _instance.Value; }
    }

    private MyClassEqualityComparer() { }

    public bool Equals(MyClass x, MyClass y)
    {
        return x.val1 == y.val1 && x.val2 == y.val2 && x.val3 == y.val3;
    }

    public int GetHashCode(MyClass obj)
    {
        return obj.val1.GetHashCode() ^ obj.val2.GetHashCode() ^ obj.val3.GetHashCode();
    }
}

有了它,您将能够使用 LINQDistinct()方法:

var distinct = lstData.Distinct(MyClassEqualityComparer.Instance).ToList();
于 2013-08-31T09:39:14.700 回答
2

假设您的真实课程MyClass覆盖Equalsand GetHashCode,您只需要添加Distinct

lstData = lstData.Distinct().ToList();
于 2013-08-31T09:33:47.027 回答