22

我有一个关于如何在 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 做到这一点?

谢谢!

4

2 回答 2

30

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

string[] collection1 = new string[] { "1", "7", "4" };
string[] collection2 = new string[] { "6", "1", "7" };

var resultSet = collection1.Intersect<string>(collection2);

foreach (string s in resultSet)
{
    Console.WriteLine(s);
}
于 2010-01-25T02:11:49.900 回答
13

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

变种查询 =
   来自 collection1 中的 str1
   在 str1 上的 collection2 中加入 str2 等于 str2
   选择str1;

foreach(查询中的 var 项)
{
     // 做一些有趣的事
     Console.WriteLine(项目);
}
于 2010-01-25T02:11:14.557 回答