Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find objects in list that match elements in array

Tags:

c#

linq

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?

like image 338
James Burani Avatar asked Mar 02 '23 10:03

James Burani


2 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));
like image 71
Cetin Basoz Avatar answered Mar 16 '23 08:03

Cetin Basoz


.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]);
}
like image 37
Frenchy Avatar answered Mar 16 '23 08:03

Frenchy