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
- ...