我有一个关于如何在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<string>(collection2);

foreach (string s in resultSet)
{
    Console.WriteLine(s);
}

其他提示

如果你想在比赛中执行任意代码,那么这将是一个LINQ-Y的方式来做到这一点。

var query = 
   from str1 in collection1 
   join str2 in collection2 on str1 equals str2
   select str1;

foreach (var item in query)
{
     // do something fun
     Console.WriteLine(item);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top