-1

I am looking for the most efficient way to code. I have a List of ints or strings and I need to know if one of the values in that list is containd in second collection.

If I use dictionary for that second collection then I came out with 5 different ways to search:

Dictionary<int, bool> dicSource = new Dictionary<int, bool>();
List<int> lstSearch = new List<int>();

// First approuce
var ids = dicSource.Keys.Intersect(lstSearch);
bool hasMatch1 = ids.Any();

//Second approuce
bool hasMatch2 = dicSource.Any(x => lstSearch.Any(y => y == x.Key));

//Third approuce
bool hasMatch3 = dicSource.Select(x => x.Key).Intersect(lstSearch).Any();

//Fourth approuce
bool hasMatch4 = (dicSource.Where(x => lstSearch.Contains(x.Key)).Count() > 0);

//Fifth approuce
for (int i = 0; i < lstSearch.Count; i++)
{
    bool hasMatch5 = dicSource.ContainsKey(lstSearch[i]);
}

On the other hand I can use another List for the second collection and then I came out with 5 different ways to search:

List<int> lst = new List<int>();
List<int> lstIds = new List<int>();

 // First approuce
 var ids = lst.Intersect(lstIds);
 bool hasMatch1 = ids.Any();

 //Second approuce
 bool hasMatch2 = lst.Any(x => lstIds.Any(y => y == x));

 //Third approuce
 bool hasMatch3 = lst.Select(x => x).Intersect(lstIds).Any(); 

 //Fourth approuce
 bool hasMatch4 = (lst.Where(id => lstIds.Contains(id)).Count() > 0);

 //Fifth approuce
 for (int i = 0; i < lstSearch.Count; i++)
 {
     bool hasMatch5 = lstSource.Contains(lstSearch[i]);
 }

Can someone please tell me what is the most efficient way to use here ?

Liran Friedman
  • 4,027
  • 13
  • 53
  • 96

1 Answers1

1

To find out the fastest one, you should performance test.

But here's another option for the mix, which will probably be faster:

var lst = new HashSet<int>();
var lstIds = new HashSet<int>();

var hasMatch = lst.Intersect(lstIds).Any();
Baldrick
  • 11,712
  • 2
  • 31
  • 35