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?
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With