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

发布于 2024-08-18 20:33:54 字数 598 浏览 2 评论 0原文

我有一个关于如何在 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 来完成此操作?

谢谢!

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.

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?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤者何惧 2024-08-25 20:33:54

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

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

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);
}
七七 2024-08-25 20:33:54

如果您想在匹配上执行任意代码,那么这将是一种 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);
}

If you want to execute arbitrary code on matches then this would be a LINQ-y way to do it.

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文