Find objects in list that match elements in array

Viewed 130

Starter code: https://dotnetfiddle.net/lJhMyo

    string[] names = { "Burke", "Laptop", "Computer", 
                       "Mobile", "Ahemed", "Sania", 
                       "Kungada", "David","United","Sinshia" };

     var empList =  new List<Employee> {
         new Employee {Name = "Burke", ID = "IHED123"},
         new Employee {Name = "David", ID = "QIUHD454"},
         new Employee {Name = "Batman", ID = "OIWQE565"},
     };

How do I construct a linq query (method syntax) that gets all Employee objects where employee name is in the "names" array?

If there is a string in "names" that is not in empList, throw exception.

EDIT: What if empList is large and I want case-insensitive match for Name?

3 Answers

You can use .Contains. ie:

var result = empList.Where(x => names.Contains(x.Name));

You can check if there is a missing name:

bool noneMissing = !names.Any(n => empList.Any(x => x.Name == n));

.Contains Tests if an array or list contains the item:

var Searched = emptList.Where(x => names.Contains(x.Name));

If Searched.Length == 0, so no Items

If you want performance use for loop (nothing is more performant) and for case insensitive use StringComparer.OrdinalIgnoreCase.

List<string> Searched = new List<string>;
for(int i = 0; i < names.Length; i++)
{
    if(emptList.contains(name[i], StringComparer.OrdinalIgnoreCase)
        Searched.Add(name[i]);
}

For large lists and case-insensitive comparison you can use HashSet with provided IEqualityComparer<string> :

var hashSet = new HashSet<string>(names, StringComparer.OrdinalIgnoreCase);
empList.Where(e => hashSet.Contains(e.Name));

And possibly moving from LINQ to for loop.

Related