I believe 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 the OR
statements? I have tried:
x.FavoriteColor == "Green" || "Blue" || "Red"
but the compiler says Operator || cannot be applied to operands of type 'bool' and 'string'
Any help is appreciated.
In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side. The following example uses the LINQ feature with method syntax to demonstrate the usage of lambda expressions: C# Copy.
Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .
The "this" and "super" references within a lambda expression are the same as in the enclosing context. Since the lambda expression doesn't define a new scope, "this" keyword within a lambda expression signifies "this" parameter of a method where the lambda expression is residing.
You can use Contains method of 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 SQL query like
SELECT ... WHERE FavoriteColor = 'Baseball' AND FavoriteColor in ("Green", "Red", "Blue")
I'd like to add that if you work with datasets which are stored in a memory you should bear in mind that List's Contains
takes O(N) iteration to get result. So if colors
contains a lot of elements you should use set HashSet instead with 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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With