How to use linq `Except` with multiple properties with different class?

南笙酒味 提交于 2019-11-29 04:50:17

You have said that you need only these objects from testListA:

  • there is not matching ProductID in testListB
  • there is existing mathing ProductID, but with different Category

So, your filter must be:

!testListB.Any(b => a.ProductID == b.ProductID && a.Category == b.Category)

So, change your code as:

testListA.Where(a => !testListB.Any(b => a.ProductID == b.ProductID && a.Category == b.Category));

Second approach:

Or you can create a new List<TestA> from the second list:

 var secondListA = testListB.Select(x=> new TestA(){Category=x.Category, ProductID=x.ProductID}).ToList();

And then create your Comparer:

sealed class MyComparer : IEqualityComparer<TestA>
{
    public bool Equals(TestA x, TestA y)
    {
        if (x == null)
            return y == null;
        else if (y == null)
            return false;
        else
            return x.ProductID == y.ProductID && x.Category == y.Category;
    }

    public int GetHashCode(TestA obj)
    {
        return obj.ProductID.GetHashCode();
    }
}

And use Except() overload which produces the set difference of two sequences by using the specified IEqualityComparer<T> to compare values.:

var result = testListA.Except(secondListA, new MyComparer ()).ToList();
S22

This is an example implementing IEqualityComparer. It should work as a concept for your purpose:

private class PKExclusiveComparer<T> : IEqualityComparer<T> where T : DataRow
{
  public bool Equals(T x, T y)
  {
    bool result = true;
    foreach (DataColumn col in (x as DataRow).Table.Columns)
    {
      if (!(x as DataRow).Table.PrimaryKey.Contains(col))
      {
        result &= x[col].Equals(y[col]);
      }
    }
    return result;
  }

  public int GetHashCode(T x)
  {
    string code = string.Empty;
    foreach (DataColumn col in (x as DataRow).Table.Columns)
    {
      if (!(x as DataRow).Table.PrimaryKey.Contains(col))
      {
        code += x[col].ToString();
      }
    }
    return code.GetHashCode();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!