如何在 C# 的通用列表中查找不匹配的记录

How to find not matching records in Generic List in C#

我有两个通用列表对象,我想获取在第二个通用列表对象中不匹配的记录。下面是我的代码。但它返回所有记录。

我想忽略第一个列表中的匹配记录。

public class CuratedIncludeUid
    {
        public string type { get; set; }
        public string uid { get; set; }
    }

List<CuratedIncludeUid> newUids = new List<CuratedIncludeUid>();
            newUids.Add(new CuratedIncludeUid { type = "series", uid = "600" });

            List<CuratedIncludeUid> liExistingUids = new List<CuratedIncludeUid>();
            liExistingUids.Add(new CuratedIncludeUid { type = "series", uid = "600" });
            liExistingUids.Add(new CuratedIncludeUid { type = "series", uid = "200" });

            var ied = liExistingUids.Except(newUids).ToList(); ;
            foreach (var row in ied)
            {
                Console.WriteLine("Uid:" + row.uid + "type:" + row.type);
            }
            Console.Read();

I am getting Output as below 
Uid:600type:series
Uid:200type:series

**My expected output as below
Uid:200type:series**

要么覆盖 Equals and GetHashCode

public class CuratedIncludeUid
{
    public string type { get; set; }
    public string uid { get; set; }

    protected bool Equals(CuratedIncludeUid other)
    {
        return string.Equals(type, other.type) && string.Equals(uid, other.uid);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        return Equals((CuratedIncludeUid) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return ((type != null ? type.GetHashCode() : 0) * 397) ^ (uid != null ? uid.GetHashCode() : 0);
        }
    }
}

或传递 IEqualityComparer to Except

public class CuratedIncludeUidEqualityComparer : IEqualityComparer<CuratedIncludeUid>
{
    public bool Equals(CuratedIncludeUid x, CuratedIncludeUid y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false;
        return string.Equals(x.type, y.type) && string.Equals(x.uid, y.uid);
    }

    public int GetHashCode(CuratedIncludeUid obj)
    {
        unchecked
        {
            return ((obj.type != null ? obj.type.GetHashCode() : 0) * 397) ^ (obj.uid != null ? obj.uid.GetHashCode() : 0);
        }
    }
}
var ied = liExistingUids.Except(newUids, new CuratedIncludeUidEqualityComparer()).ToList();

您可以实施 EqualsGetHashCodeIEqualityComparer,或者您也可以执行以下操作:

All:

var ied = liExistingUids.Except(newUids).ToList();
liExistingUids
  .Where(x => newUids.All(y => y.type != x.type && y.series != x.series))
  .ToList();

Any:

liExistingUids
  .Where(x => !newUids.Any(y => y.type == x.type && y.series == x.series))
  .ToList();