开发者

Why Except function applying Distinct? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Except has similar effect to Distinct?

I'm having two List<String> like

lstOne = { "A", "B", "C" ,"C" ,"C" };
lstTwo = { "A" };

lstResult = lstOne.Except(lstTwo).ToList();

Now the expected output is

lstReult = { "B","C","C","C" };

But the actula result is like

lstR开发者_运维问答esult = { "B","C" };

Why its so? i've used Except , why its applying Distinct too?


"Except" is documented as returning the set difference of two sequences.

The set difference by definition is a set. Sets by definition don't have duplicates.

the expected output is ...

No, the expected output is identical to the actual output.

If you expect something different, my advice is to adjust your expectations to match the documented behaviour.


It is documented as returning "A sequence that contains the set difference of the elements of two sequences.". Sets do not have duplicates.

It is perhaps a subtle point, but it functions as per the spec.

If you want the dups:

var lstOne = new[] { "A", "B", "C" ,"C" ,"C" };
var except = new HashSet<string> { "A" };

var lstResult = lstOne.Where(x => !except.Contains(x)).ToList();
   // ^^ "B", "C", "C", "C"


MSDN Definition: "Produces the set difference of two sequences by using the default equality comparer to compare values." --> Difference as set --> each key is unique.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜