Lambda expression using the OR operator

I believe that there is a better way to write this, but I am experiencing a mental block.

int num = 0; using(var db = new TestDB()) { num = db.Table.Where(x => x.FavoriteSport == "Baseball" && (x.FavoriteColor == "Green" || x.FavoriteColor == "Blue" || x.FavoriteColor == "Red")).Count(); } return num; 

Is there a better way to write OR instructions? I tried:

 x.FavoriteColor == "Green" || "Blue" || "Red" 

but the compiler says Operator || cannot be applied to operands of type 'bool' and 'string' Operator || cannot be applied to operands of type 'bool' and 'string'

Any help is appreciated.

+5
source share
4 answers

You can use the Contains method array / list / hashset.

 var colors = new List<string> {"Green", "Red", "Blue" }; db.Table.Where(x => x.FavoriteSport == "Baseball" && (colors.Contains (x.FavoriteColor)).Count() 

It will generate an SQL query, for example

 SELECT ... WHERE FavoriteColor = 'Baseball' AND FavoriteColor in ("Green", "Red", "Blue") 

I would like to add that if you are working with data sets that are stored in memory, you must remember that List Contains performs O (N) iteration to get the result. Therefore, if colors contains many elements, you should instead use a HashSet instead of O (1).

 var colors = new HashSet<string> {"Green", "Red", "Blue", .... }; someDataSet.Where(x => x.FavoriteSport == "Baseball" && (colors.Contains (x.FavoriteColor)).Count() 

You can find List-HashSet performance comparison here.

+7
source
 string[] FavColor = new string[]{"Green","Red","Blue"}; int num = 0; using(var db = new TestDB()) { num = db.Table.Where(x => x.FavoriteSport == "Baseball" &&FavColor.Any(x.FavoriteSport)).Count(); } return num; 
+4
source

You can use the object container and use the Contains method. For instance:

 var favoriteColors = new List<string> { "Blue", "Green", "Red" }; var num = 0; using(var db = new TestDB()) { num = db.Table.Where(x => x.FavoriteSport == "Baseball" && favoriteColors.Contains(x.FavoriteColor)).Count(); } 

I would check the profile to make sure that the generated SQL uses the IN statement.

+3
source

pretty much what everyone said - you can create a collection of valid strings and see if your string is listed in this collection. You can do it inline:

 num = db.Table.Count(x => x.FavoriteSport == "Baseball" && new []{"Green","Red","Blue"}.Contains(x.FavoriteColor); 

It is worth noting that you can directly change your Where out to Count

+3
source

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


All Articles