I want to convert this code to a linq solution. What it does it looks into a collection of customers and see if at least one of the has a middle name. This code works fine, I’m just trying to learn linq, so looking for an alternative solution.:
//Customers - List<Customer>
private bool checkMiddleName()
{
foreach (Customer i in Customers)
{
if (i.HasMiddleName == true)
{
return true;
}
}
return false;
}
I tried to write something like: (Customers.Foreach(x=>x.HasMiddleName==true)...
but looks line it’s not the method I’m looking for.
If you just want to know if theres at least one, you can use
Enumerable.Any:If you want to know the first matching customer, you can use
Enumerable.FirstorEnumerable.FirstOrDefaultto find the first customer withMiddleName==true:Firstthrows an InvalidOperationException if the source sequence is empty, whereasFirstOrDefaultreturnsnullif there’s no match.