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

时间:2019-01-10 22:56:32

标签: c# linq generic-list except

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

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

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**

2 个答案:

答案 0 :(得分:1)

覆盖EqualsGetHashCode

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传递给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();

答案 1 :(得分:-1)

您可以实施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();