3

我在互联网上搜索了一段时间,但找不到我真正需要的东西。我的问题是我有两个 linq 语句,我计划将它们放在 UNION 中,以便将它们合并到一组列表中,但我想删除那些重复的值。具体来说,这里是一个场景:

query 1 = "this is a test","Yes", "This is a remark"
          "this is a test2","No", "This is the second remark"

query 2 = "this is a test","",""
          "this is a test2","",""
          "this is a test3","",""
          "this is a test4","",""

现在我想要发生的是这样的:

          "this is a test","Yes", "This is a remark"
          "this is a test2","No", "This is the second remark",
          "this is a test3","",""
          "this is a test4","",""

我怎样才能在 LINQ 中做到这一点?提前谢谢!

4

3 回答 3

4

您可以使用以下查询:

var result = from item in query2
             let match = query1.SingleOrDefault (e => e[0] == item[0])
             select match ?? item;

这将遍历query2,并且对于它用于SingleOrDefault查找项目query1的第一个元素匹配的项目的每个项目,或null。然后select产生名为 match from 的项目(query1如果不是)null,或者是 的当前项目query2


另一种可能更快的方法是创建一个适当的IEqualityComparer和 using Union,如下所示:

class FirstElementComparer : IEqualityComparer<string[]>
{
    //TODO error checking
    public bool Equals(string[] a, string[] b)
    {       
        return a[0].Equals(b[0]);
    }

    public Int32 GetHashCode(string[] obj)
    {
        return obj[0].GetHashCode();
    }
}

并像这样使用它:

void Main()
{
    string[][] query1 = {new [] {"this is a test","Yes", "This is a remark"},
                         new [] {"this is a test2","No", "This is the second remark"}};

    string[][] query2 = {new [] {"this is a test","",""},
                         new [] {"this is a test2","",""},
                         new [] {"this is a test3","",""},
                         new [] {"this is a test4","",""}};

    query1.Union(query2, new FirstElementComparer()).Dump();                         
}

EqualityComparer用于将Unionin 中query1的元素与 中的元素进行比较query2。它仅通过比较每个数组中的第一项来实现。


结果:

在此处输入图像描述

于 2013-05-08T09:17:04.863 回答
3

像这样的东西...

query1.Union(query2).GroupBy(q => q[0]).Select(grp => grp.FirstOrDefault());

(未测试)

于 2013-05-08T09:57:41.397 回答
-2

尝试使用 .Distinct()。有关更多信息,请参见下面的链接:

LINQ:不同的值

于 2013-05-08T09:35:58.447 回答