简体   繁体   中英

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.

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

You have many ways to do this. It mostly depends on the data you're trying to match.

  • First thing you can do is having a sorted list
  • then if you know the middle value of the list you can iterate through your list from the beginning of from the end
  • but mostly just return your value since you've found it

also the first 2 points will only work if your list has some numeric value on which you can rely to identify an item.

The first optimization you can do is:

Foreach (var item1 in List1)
{
   Foreach (var item2 in List2 )
   {
       if(item2 == item1) return item1;
   }
}

If you really need this routine to be very fast you'll have to do optimizations based on the data that is in your lists.

Also if your data is string in both lists, you can generate an hashcode for each string ( string.GetHashCode ) and then rely on the hascode to sort and search in your lists.

There are many other ways, but it all depends on:

  • the amount of data you have in your lists (if you only have 100 elements you won't see a lot of performance gains)
  • if your lists are static or dynamic
  • how often they can change if they are dynamic
  • how often do you make a search in these lists
  • ...

You can short-circuit the loops when you find any matches. You could then use a method that returns the item that matches, or null if none matched (assuming the elements are references types):

foreach (var item1 in List1)
    foreach (var item2 in List2)
        if (item2 == item1)
            return item1;

return null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM