Enumerable.Except方法

     今天看到个说获取数组中重复项的题目,网上也有很多答案。然后自己也想也下,于是就有了下面的代码

Int32[] testArray = { 1, 2, 6, 4, 8, 6, 8 };
var nonDupList = testArray.Distinct();
var dupNumbers = testArray.Except(nonDupList);

     咋一看,好像是那么回事,先把testArray中重复项过滤掉放入nonDupList中,然后再用Except方法把两个数组的交集获得,也就是重复项。代码很完美。

     可运行上面代码不是那么回事,dupNumbers里面什么也没有。接着就看MSDN,下面是解释:

"Produces the set difference of two sequences by using the default equality comparer to compare values.”

      写得很好,通俗易懂。注解上写了一句话:This method returns those elements in first that do not appear in second. It does not also return those elements in second that do not appear in first.

     意思是从first里面返回没有出现在second里面的元素。好像这个可以解释我上面的代码应该返回6和8。通篇文档中没看到说会把第一个参数中的重复项先过滤后再调用Except方法。然后上当了。

posted @ 2013-04-20 18:21  Navono  阅读(344)  评论(0编辑  收藏  举报