linq查本集合中不包含于另一个集合的元素

int[] num0 = { 28, 32, 14 };
int[] num1 = {14,15,16};

如上,我想把num0中不包含于num1的元素都找出来,其正确结果应该是28,32。早上看到原来linq可以写多个from字句,之后就想到了这样的写法:

int[] num0 = { 28, 32, 14 };
int[] num1 = {14,15,16};

var qq = from n1 in num0
from n2 in num1
where n1 != n2
select n1;

结果,我错了,调试了一下才知道自己想当然了。结果如下:

总共进行了3 * 3,9次比较,那个语句把所有成立的n1都选进去了。

所以还是老老实实用contains好了

int[] num0 = { 28, 32, 14 };
int[] num1 = { 14, 15, 16 };

var bb = from n1 in num0
where num1.Contains(n1) == false
select n1;

另外,推荐一个工具:LinqPad,我的这个例子就是用linqPad 调试的,上面那个结果显示使用了语句:qq.Dump();

网址:http://www.linqpad.net/

下载:

      for .net 3.5:http://www.linqpad.net/GetFile.aspx?LINQPad.exe

      for .net 4.0:http://www.linqpad.net/GetFile.aspx?LINQPad4.zip
这个工具还不错,自带了许多例子,还可以写入自己的语句运行。

另外,微软官方的Official Visual Studio 2008 C# Samples里面的LINQ - Sample Queries也是不错的,带了许多例子,几乎所有的linq特性都有,还可以执行。

网址:http://code.msdn.microsoft.com/csharpsamples

LINQ - Sample Queries 截图:

 

2012年1月13日16:56:23 更新:

后来又找到了Except、Intersect、Union、Distinct等方法,终于可以排除一个集合中那些某个属性的值存在于另一个几个中元素属性的方法了。

按照Example上的例子,大概可以如此实现:

public void Linq53() {
List<Product> products = GetProductList();
List<Customer> customers = GetCustomerList();

var productFirstChars =
from prod in products
select prod.ProductName[0];
var customerFirstChars =
from cust in customers
select cust.CompanyName[0];

var productOnlyFirstChars = productFirstChars.Except(customerFirstChars);

Console.WriteLine("First letters from Product names, but not from Customer names:");
foreach (var ch in productOnlyFirstChars) {
Console.WriteLine(ch);
}
}



posted @ 2012-01-13 10:53  果壳中的宇宙  阅读(17014)  评论(1编辑  收藏  举报