用C#中的列组合筛选唯一数据

本文关键字:筛选 唯一 数据 组合 | 更新日期: 2023-09-27 18:29:47

我有一个列表如下:

 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"}

我想消除重复的行,并将不同的行从列表中删除。我该怎么做?

用C#中的列组合筛选唯一数据

var result = lstData.GroupBy(x=>new {x.val1, x.val2, x.val3}, (x,y)=>y.First())
                    .ToList();                        

假设您的真实类MyClass覆盖EqualsGetHashCode,您只需要添加Distinct:

lstData = lstData.Distinct().ToList();

您必须在MyClass类上实现GetHashCodeEquals方法,或者定义实现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();
    }
}

有了它,您就可以使用LINQ Distinct()方法:

var distinct = lstData.Distinct(MyClassEqualityComparer.Instance).ToList();