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
:
bool atLeastOneCustomerWithMiddleName = Customers.Any(c => c.HasMiddleName);
If you want to know the first matching customer, you can use Enumerable.First
or Enumerable.FirstOrDefault
to find the first customer with MiddleName==true
:
var customer = Customers.FirstOrDefault(c => c.HasMiddleName);
if(customer != null)
{
// there is at least one customer with HasMiddleName == true
}
First
throws an InvalidOperationException if the source sequence is empty, whereas FirstOrDefault
returns null
if there's no match.
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