匹配元素之间的2个集合与Linq在c# [英] Match elements between 2 collections with Linq in c#

查看:225
本文介绍了匹配元素之间的2个集合与Linq在c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a question about how to do a common programming task in 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.

例如:

        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做到这一点。

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?

谢谢!

推荐答案

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

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

这篇关于匹配元素之间的2个集合与Linq在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆