简体   繁体   English

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

[英]Match elements between 2 collections with Linq in c#

i have a question about how to do a common programming task in linq. 我有一个关于如何在linq中执行常见编程任务的问题。

lets say we have do different collections or arrays. 假设我们已经做了不同的集合或数组。 What i would like to do is match elements between arrays and if there is a match then do something with that element. 我想要做的是匹配数组之间的元素,如果有匹配,那么用该元素做一些事情。

eg: 例如:

        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///
                }
            }
        }

This can obviously be accomplished using the code above but what i am wondering if there is a fast and neat way you can do this with LinqtoObjects? 这显然可以使用上面的代码完成,但我想知道是否有一个快速和简洁的方法,你可以用LinqtoObjects做到这一点?

Thanks! 谢谢!

Yes, intersect - Code sample to illustrate. 是的,相交 - 代码示例来说明。

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);
}

If you want to execute arbitrary code on matches then this would be a LINQ-y way to do it. 如果你想在匹配上执行任意代码,那么这将是一种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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM