The first match in the collection

I want to convert this code to linq solution. What he does, he looks into the collection of clients and sees at least one of them has a middle name. This code works fine, I'm just trying to learn linq, so I am 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 it doesn't look the way I'm looking.

+6
source share
4 answers

If you just want to know if there is at least one of them, you can use Enumerable.Any :

 bool atLeastOneCustomerWithMiddleName = Customers.Any(c => c.HasMiddleName); 

If you want to know the first suitable client, you can use Enumerable.First or Enumerable.FirstOrDefault to find the first client 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, and FirstOrDefault returns null if there is no match.

+18
source
 var result = Customers.Where(x=>x.HasMiddleName == true).FirstOrDefault(); 
+2
source

Based on this:

What he does, he looks through a collection of clients and sees if at least one of them has a middle name.

Try

 return Customers.Where(x => x.HasMiddleName).Any(); 

This query returns true if at least one custmer has the property HasMiddleName = true

+1
source

You can use the following to achieve what you need:

 Customers.Where(cust=> cust.HasMiddleName).Count > 0 

So, if Count is greater than zero, then you have clients that have a middle name.

Or for better performance you can say:

 bool customerWithMiddleName; foreach(Customer cust in Customers) { if(cust.HasMiddleName) { customerWithMiddleName = true; break; } } 
0
source

Source: https://habr.com/ru/post/920922/


All Articles