c# - 根据某些字段获取两个列表之间的差异

标签 c# linq join left-join list-comparison

我是 LINQ 的新手,我可能已经把自己逼到了一个角落。我有两个列表(左和右),我需要:

a) 根据特定字段获取匹配项

b) 获取左侧没有匹配项的项,右侧没有匹配项

c) 获取右侧的项目而左侧没有匹配项

如果某些字段相等,则找到匹配项。其他字段可能包含也可能不包含值,但不得影响匹配比较。

为了得到项目a,我在两个列表上执行了一个JOIN:

var q = from a in r1
        from b in r2
        where a.Prop1 == b.Prop1 && a.Prop3 == b.Prop3
        select new { a.Prop1, a.Prop2, b.Prop3 };

我不确定从这里到哪里去。我认为我不能使用.Except(),因为两个列表的其他属性不同,可能导致比较失败。

我还尝试使用 Left Join 并获取没有匹配项的项目:

 var q =
     from c in r1
     join p in r2 on c.Prop1 equals p.Prop1
     into cp
     from p in cp.DefaultIfEmpty()
     select new { Prop1 = c.Prop1, Prop2 = p == null ? "N/A" : p.Prop2 };

但是我发现您不能比较多个字段。

在 LINQ 的 Left Join 上可以有多个字段吗? 是否有其他方法(除了 LINQ)来获取两个列表之间的差异?

最佳答案

这使用了 IntersectExcept(类似于 Cuong Le 的解决方案):

public class MyComparer : IEqualityComparer<YourClass>
{
    #region IEqualityComparer<YourClass> Members

    public bool Equals(YourClass x, YourClass y)
    {
        return
            x.Prop1.Equals(y.Prop1) && x.Prop3.Equals(y.Prop3);
    }

    public int GetHashCode(YourClass obj)
    {
        int hCode = obj.Prop1.GetHashCode() ^ obj.Prop3.GetHashCode();
        return hCode.GetHashCode();
    }

    #endregion
}

// matched elements from both lists
var r1 = l1.Intersect<YourClass>(l2, new MyComparer());
// elements from l1 not in l2
var r2 = l1.Except<YourClass>(l2, new MyComparer());
// elements from l2 not in l1
var r3 = l2.Except<YourClass>(l1, new MyComparer());

关于c# - 根据某些字段获取两个列表之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12598558/

相关文章:

c# - 如何在 linq 表达式中格式化字符串?

sql - 连接来自不同数据库的表 (PostgreSQL)

c# - 不存在从 ObjectParameter 到已知托管提供程序 native 类型的映射

c# - 如何使用 IDispatch 从非托管 C++ 调用 C# dll?

c# - SHIFT+ENTER 写入 Interop.Word 文档的击键是什么

mysql - 不确定这个右外连接的结果是什么

来自两个连接表和多行的 MySQL 总和 - 需要取出全部或所有行

c# - StackExchange.Redis ListRightPop 不等待结果

c# - 如何创建 IEnumerable<T> 的浅拷贝?

c# - LINQ 嵌套组性能