More concise LINQ with "or" clause

I have a small LINQ query containing a Where clause; sort of:

    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 briefly using LINQ. In SQL, I could write a similar WHERE clause, for example:

WHERE bike.Color IN ('Red','Blue','Green')
+4
source share
1 answer

You can use the LINQ method Containsto check the color of your item for 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));
+8
source

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


All Articles