Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare List and return matches in c#

What is the fastest and best way to compare 2 lists and return a match. Only one match is possible. List1 contains dynamic data from a database.

The way I do it now :

foreach (var item1 in List1)
{
   foreach (var item2 in List2 )
   {
       if(item2 == item1)
       string match = item1;
   }
}

I have a feeling like it can be done a lot faster.

like image 386
Bernardmoes Avatar asked May 08 '13 07:05

Bernardmoes


People also ask

Can you compare lists with ==?

Further, the == operator is used to compare the list, element by element.

How do you compare elements in a list?

Using sum() ,zip() and len() This method first compares each element of the two lists and store those as summation of 1, which is then compared with the length of the other list. For this method, we have to first check if the lengths of both the lists are equal before performing this computation.

Can we compare two lists in C#?

By using Intersect , we can check which elements in source list are also contained in compare list. var source = new List<string>() { "a", "b", "c" }; var compare = new List<string>() { "b", "c", "d" }; var result = source. Intersect(compare);


1 Answers

Use Enumerable.Intersect.

var matchItem = List1.Intersect(List2).First();

Not really sure how much it is faster to your current code, you can measure it using Stopwatch. But in your current code you should break your inner as well as outer loop on finding the match. Something like:

foreach (var item1 in List1)
{
    string match = null;
    foreach (var item2 in List2)
    {
        if (item2 == item1)
        {
            match = item1;
            break;
        }
    }
    if (match != null)
        break;
}
like image 113
Habib Avatar answered Sep 19 '22 04:09

Habib