Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get First Single matched element or First if there's no match?

Is that possible in LINQ to write a nice one-liner to get a first matched element or if there's no match than get first element in the collection?

E.g. you have a collection of parrots and you want yellow parrot but if there's no yellow parrots - then any will do, something like this:

Parrots.MatchedOrFirst(x => x.Yellow == true)

I'm trying to avoid double-go to SQL Server and the ORM we use in this particular case is Dapper.

like image 827
user1249170 Avatar asked Oct 18 '25 10:10

user1249170


2 Answers

What about:

var matchedOrFirst = Parrots.FirstOrDefault(x => x.Yellow == true) 
    ?? Parrots.FirstOrDefault();

Edit

For structs, this should work:

var matchedOrFirst = Parrots.Any(x => x.Yellow == true) 
    ? Parrots.First(x => x.Yellow == true)
    : Parrots.FirstOrDefault();
like image 52
Rufus L Avatar answered Oct 19 '25 23:10

Rufus L


Edit: It was a linq to SQL solution

First building a handy extension

public static T MatchedOrFirstOrDefault<T>(this IQueryable<T> collection, System.Linq.Expressions.Expression<Func<T, Boolean>> predicate)
{
  return (from item in collection.Where(predicate) select item)
                    .Concat((from item in collection select item).Take(1))
                    .ToList() // Convert to query result
                    .FirstOrDefault();
}

Using the code

var matchedOrFirst = Parrots.MatchedOrFirstOrDefault(x => x.Yellow);
like image 44
Eric Avatar answered Oct 20 '25 01:10

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!