简体   繁体   English

Enumerable.Except 问题

[英]Enumerable.Except Problem

Can someone explain why this doesn't work like I think it should.有人可以解释为什么这不像我认为的那样有效。

double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.3, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };

IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);

foreach (double number in onlyInFirstSet)
    Console.WriteLine(number);

/*
 This code produces the following output:

 2
 2.1
 2.3
 2.4
 2.5
*/

What I would expect is 2, 2.1, 2.3, 2.3, 2.3, 2.4, 2.5.我期望的是 2、2.1、2.3、2.3、2.3、2.4、2.5。 Why would except return a distinct list?为什么除了返回一个不同的列表? Is this a bug?这是一个错误吗?

Update:更新:

Ok, totally missed that point in the docs.好的,完全错过了文档中的这一点。 Funny 4 people respond with the same answer.有趣的 4 人回答相同的答案。 You would think you would just up vote the guy who answered it first.:)你会认为你会投票给第一个回答的人。:)

Why would except return a distinct list?为什么除了返回一个不同的列表? Is this a bug?这是一个错误吗?

Nope.没有。 Except produces a set difference . Except产生一组差异 See the documentation :请参阅文档

Produces the set difference of two sequences by using the default equality comparer to compare values.通过使用默认相等比较器比较值来产生两个序列的集合差。

To do what you want, just use Where to filter the values appropriately.要执行您想要的操作,只需使用Where适当地过滤值。 For example:例如:

"abcdddefffg".Where(e => !"cde".Contains(e));       // Produces "abfffg".

This is actually the correct behaviour.这实际上是正确的行为。 The Except method is documented to return the set difference of the two IEnumerable arguments.记录了Except方法以返回两个 IEnumerable arguments 的设置差异。 Since by definition, sets cannot contain duplicate elements, these are eliminated in the result.由于根据定义,集合不能包含重复元素,因此这些元素在结果中被消除。 See the MSDN docs for more info.有关详细信息,请参阅MSDN 文档

Because "Except" is a "set" function, and the concept of a "set" is defined as a unique list of items.因为“除外”是一个“集合”function,而“集合”的概念被定义为一个唯一的项目列表。 In other words, sets by definition cannot contain duplicates.换句话说,根据定义,集合不能包含重复项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM