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.
Further, the == operator is used to compare the list, element by element.
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.
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);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With