Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

union in two linq statements and remove the duplicate

Tags:

c#

linq

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

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

like image 826
Clyde Avatar asked Dec 03 '25 18:12

Clyde


1 Answers

You could use the following query:

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

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.


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

and use it like this:

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

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.


Result:

enter image description here

like image 190
sloth Avatar answered Dec 06 '25 08:12

sloth