【问题标题】:Compare two collections with LINQ使用 LINQ 比较两个集合
【发布时间】:2014-12-10 14:05:39
【问题描述】:

我有两个来自 Type 的集合,这样说:

MyType
{
    public bool isDifferent = false;
    private string str;
    public int n;
}

ObservableCollection<MyType> c1;
ObservableCollection<MyType> c2;

我想比较 c1 和 c2,如果它们不同,则将 c1 的 isDifferent 设置为 True,并将 c2 的 isDifferent 设置为保持这种状态。如何使用 LINQ 实现这一点。我还想知道当 isDifferent 总是不一样时,比较将如何发生。也许有些人专门为 isDifferent memeber 排除 linq 子句。

【问题讨论】:

标签: c# linq linq-to-sql collections comparison


【解决方案1】:

Linq 中尝试这样的操作。虽然你没有告诉参与比对集合的业务

c1.Except(c2).Union(c2.Except(c1)).Select(your properties);

使用 SymmetricExceptWith

var c1= new HashSet<T>(a);
var c2 = new HashSet<T>(b);
c1.SymmetricExceptWith(c2);

【讨论】:

  • ExceptUnionHashSet&lt;MyType&gt; 如何知道哪些对象相等?除此之外,我假设 OP 想要更新 IsDifferentc1("set isDifferent of c1 to True and isDifferent of c2 to stay like this")。
  • 同意你的看法。实际上我认为 OP 想要比较这两个列表并从两个集合中弹出相似的项目。
【解决方案2】:

LINQ 提供了Zip 方法,可让您在一个循环中遍历两个集合:

foreach (var p in c1.Zip(c2, (a, b) => new {a, b}) {
    // p.a represents the first element; p.b is the second element
    if (!CompareMyType(p.a, p.b)) {
        // Set properties of p.a or p.b here:
        p.a.isDifferent = true;
    }
}

请注意,此代码允许您根据两个集合中的项目序列测试成对相等性,因此集合内的顺序很重要。

【讨论】:

    猜你喜欢
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2013-04-26
    相关资源
    最近更新 更多