在两个linq语句中合并并删除重复项 [英] union in two linq statements and remove the duplicate

查看:93
本文介绍了在两个linq语句中合并并删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been searching for a while in the internet yet cant find what i really needed. My problem is that I have two linq statements which I am planning to have them in UNION so that they'll be mergen into 1 single set of list but I want to removed those duplicate values. To be specific here is the a scenario:

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","",""

现在我想发生的事情是这样的:

now what I want to happen is something like this:

          "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中做到这一点?谢谢!!

How can I do this in LINQ?thanks in advance!

推荐答案

您可以使用以下查询:

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

这将遍历query2,对于每个项目,它使用SingleOrDefaultquery1中找到与项目的第一个元素匹配的项目,即null.然后select会从query1生成一个名为match的项目(如果不是null的话),或者是当前的query2项.

This will iterate over query2, and for each item it uses SingleOrDefault to find the item in query1 where the first elements of the items match, or null. Then the select yields either the item called match from query1, if it is not null, or the current item of query2.

另一种可能更快的方法是创建一个合适的IEqualityComparer并使用Union,如下所示:

Another, probably faster approach is to create an appropriate IEqualityComparer and using Union, like this:

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

Union使用EqualityComparerquery1中的元素与query2中的元素进行比较.只需比较每个数组中的第一项即可.

The EqualityComparer is used by Union to compare the elements in query1 with the elements in query2. It does so by just comparing the first item in each array.

结果:

这篇关于在两个linq语句中合并并删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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