Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More concise LINQ with 'or' clause

I have a small LINQ query containing a Where clause; something like:

    var blueRedGreenBikes = GetBikes(filter)
.Where(a => a.Color == "Blue" || a.Color == "Red" || a.Color == "Green")
.Count()

I am looking for a way to write this type of query more concisely using LINQ. In SQL, I might write a similar WHERE clause like:

WHERE bike.Color IN ('Red','Blue','Green')
like image 792
Wes Doyle Avatar asked Feb 08 '23 23:02

Wes Doyle


1 Answers

You can use the LINQ Contains method to check your item's color against a collection.

var colorList=new List<string> { "Blue","Red","Green"};

var blueRedGreenBikes = GetBikes(filter).Where(a => colorList.Contains(a.Color)).Count();

Another version

var blueRedGreenBikes = GetBikes(filter).Count(s => colorList.Contains(s.Color));
like image 126
Shyju Avatar answered Feb 12 '23 10:02

Shyju