【问题标题】:Set of values in one or other list but not both一个或另一个列表中的一组值,但不是两者
【发布时间】:2013-02-05 21:21:06
【问题描述】:

我正在区分两个字典,并且我想要 or 或其他字典中的所有键的集合,但不是两者(我不关心顺序)。由于这仅涉及键,因此我们可以使用字典键的 IEnumerables 来完成此操作。

简单的方法,涉及2遍:

return first.Keys.Except(second.Keys).Concat(second.Keys.Except(first.Keys));

我们可以连接,因为例外保证列表将完全不同。

但我感觉有一种更好、更灵活的方法。

【问题讨论】:

  • LINQ and set difference 的可能重复项
  • 所以你想要不重复的不同值列表?
  • 我愿意,是的,因此这是一个骗局。以前没有看到。投票结束。

标签: c# linq


【解决方案1】:

我更喜欢非 LINQy 方式:

var set = new HashSet<KeyType>(first.Keys);
set.SymmetricExceptWith(second.Keys);

这是您的另一种(但不是更好的)LINQy 方式:

var result = first.Keys.Union(second.Keys)
                       .Except(first.Keys.Intersect(second.Keys));

如果您正在寻找(可能)性能更高的东西:

var result = new HashSet<KeyType>();

foreach(var firstKey in first.Keys)
{
    if(!second.ContainsKey(firstKey))
        result.Add(firstKey);    
}

foreach(var secondKey in second.Keys)
{
    if(!first.ContainsKey(secondKey))
        result.Add(secondKey);    
}

【讨论】:

    猜你喜欢
    • 2015-12-21
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2017-02-28
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多