【问题标题】:Match elements between 2 collections with Linq in c#在c#中使用Linq匹配2个集合之间的元素
【发布时间】:2011-01-08 22:40:34
【问题描述】:

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

谢谢!

【问题讨论】:

  • 这将取决于 // DO SOMETHING EXCITING/// 这甚至可能是不可能的,因为 Ling 是基于 IEnumerable 的,而这段代码可以做任何事情。 Linq 为您构建数据结构。 //做一些令人兴奋的事情///做什么?
  • 顺便说一句,您可以通过使用集合数据结构的两个实例将 O(n^2) 减少到 O(n)。

标签: c# linq collections elements matching


【解决方案1】:

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

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

foreach(查询中的 var 项)
{
     // 做一些有趣的事
     Console.WriteLine(项目);
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • Intersect 是最干净的,但是你为什么用'union'这个名字呢?
    • 因为我在看圣徒 - 维京人的比赛,有点分心。好点 - 我会编辑它
    • 如果集合是不同的类,而 classa.string 需要匹配 classb.string
    • 在 Python 中,您有时可以提供一个 lambda,类似于:m = min(coll, key = lambda x: x.field1)。它的作用是计算具有最小值的最小元素,名为“field1”。我认为 Lambdas 也与 Linq 一起使用。我不是这方面的专家,但如果 Intersect 将 lambda 作为可选参数,那就太好了。
    • 忘了提一下,在 Python 中,您还可以向 min 提供 cmp 参数:m = min(coll, cmp = lambda x,y: x.field1 - y.field1) - 应该实现同样的结果。我敢肯定,您可以想到 cmp= 的其他用途。
    猜你喜欢
    • 2013-07-23
    • 2021-08-19
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多