I have two List<string> (listOfFullPaths containg full database paths for e.g. “C:\MyDir\SomeDir\SomeDatabase.mdf”) and some other List<string> containing some of the names of the databases (only) (‘listOfDatabases’). So each might include
List<string> listOfFullPaths = new List<string>()
{
"C:\MyDir\SomeDir\SomeDatabase1.mdf",
"C:\MyDir\SomeDir\SomeDatabase2.mdf",
"C:\MyDir\SomeDir\SomeDatabase3.mdf"
};
the other just
List<string> listOfFullPaths = new List<string>()
{
"SomeDatabase1",
"SomeDatabase2"
};
My question is what is the most efficent way of returning the full paths contined in listOfFullPaths that have their corresponding database in listOfDatabases?
Note: The answer is not something like
List<string> tmpList = new List<string>();
foreach (string database in listOfDatabases)
if (listOfFullPaths.Contains(database))
tmpList.Add(database);
listOfFullPaths.Clear();
listOfFullPaths = tmpList;
although this does what I want.
If you want to do it efficiently in terms of speed (i.e. in O(n)) then JaredPar’s answer is correct.
Here is a more idiomatic version: