Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First match in a collection

Tags:

c#

linq

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.

like image 938
user194076 Avatar asked Jul 19 '12 22:07

user194076


1 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.

like image 119
Tim Schmelter Avatar answered Sep 28 '22 16:09

Tim Schmelter