First match in a collection

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.

Answers


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.


var result   = Customers.Where(x=>x.HasMiddleName == true).FirstOrDefault();

Based on this:

What it does it looks into a collection of customers and see if at least one of the has a middle name.

Try

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

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


You may use the following to achieve what you need:

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

So , if Count is more than zero means you have some customers who have Middle name.

Or for better performance you may say:

bool customerWithMiddleName;

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

Need Your Help

How do I get formatted JSON in .NET using C#?

c# .net json javascriptserializer

I am using .NET JSON parser and would like to serialize my config file so it is readable. So instead of: