【问题标题】:Is the order of an except and intersect operation always ignorable?except 和 intersect 操作的顺序是否总是可以忽略的?
【发布时间】:2014-12-31 12:24:01
【问题描述】:

对我来说,似乎任何操作都像

var list = new List<int>();
// list.Add some elements...
list.Except(anotherList).Intersect(yetAnotherList)

这总是一样吗:

list.Intersect(yetAnotherList).Except(anotherList)

我不是 100% 确定。

感谢您的帮助。

【问题讨论】:

    标签: c# linq list intersect except


    【解决方案1】:

    从纯粹的集合论的角度来看,顺序在这里并不重要。在这两个步骤中,您只是从list 中删除元素。如果元素在anotherList 中或不在yetAnotherList 中,则从列表中删除它。是否切换上句中的 »or« 的操作数并没有什么区别。

    为了说明,让我们构造三个列表(这里是集合,因为它们是集合操作):

    list = { A, B, C, D }
    anotherList = { A, B, E, F }
    yetAnotherList = { A, C, E, G }
    

    这里的每个集合都有一个元素在所有三个集合 (A) 中,一个元素在其他每个集合中,一个元素仅在该集合中而不在其他集合中。所以我们在这里涵盖了所有可能的交集和集差的情况。

    list.Except(anotherList) 产生{ C, D }。与yetAnotherList 相交会产生{ C }

    list.Intersect(yetAnotherList) 产生{ A, C }。排除anotherList 再次产生{ C }

    【讨论】:

    • 还应该注意IntesectExcept 都保留了元素的原始顺序 - 因此两个版本产生相同的结果。
    • 你的第二句话是不正确的......有点奇怪的表达方式。我认为你的意思是你得到了一个列表,其中包含了 yetAnotherList 中的所有元素,但没有 anotherList 中的元素。
    • @Joey "没有 yetAnotherList 中的所有元素以及没有 yetAnotherList 中的所有元素" 将不会产生任何结果。
    • decPL:啊,现在说得通了。我将此评论视为对我的双重否定措辞的投诉,而不是实际的事实错误。
    • 啊,Intersect 保证订单,但Except 不保证。
    猜你喜欢
    • 1970-01-01
    • 2011-01-18
    • 2023-01-30
    • 2021-10-01
    • 1970-01-01
    • 2012-07-16
    • 2020-06-03
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多