在c#中使用Linq匹配2个集合之间的元素

我有一个关于如何在linq中执行常见编程任务的问题。

假设我们已经做了不同的集合或数组。 我想做的是匹配数组之间的元素,如果有匹配,那么用该元素做一些事情。

例如:

string[] collection1 = new string[] { "1", "7", "4" }; string[] collection2 = new string[] { "6", "1", "7" }; foreach (string str1 in collection1) { foreach (string str2 in collection2) { if (str1 == str2) { // DO SOMETHING EXCITING/// } } } 

这显然可以使用上面的代码完成,但我想知道是否有一个快速和简洁的方法,你可以用LinqtoObjects做到这一点?

谢谢!

是,相交 – 代码示例来说明。

 string[] collection1 = new string[] { "1", "7", "4" }; string[] collection2 = new string[] { "6", "1", "7" }; var resultSet = collection1.Intersect(collection2); foreach (string s in resultSet) { Console.WriteLine(s); } 

如果你想在匹配上执行任意代码,那么这将是一种LINQ-y方式。

  var query = 
   来自collection1中的str1 
   在str1上的collection2中加入str2等于str2
   选择str1;

 foreach(查询中的var项)
 {
      //做一些有趣的事
      Console.WriteLine(项目);
 }