Reputation: 5943
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.
Upvotes: 8
Views: 14183
Reputation: 5488
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
Upvotes: 11
Reputation: 25370
pretty much what everyone has said - you can make a collection of valid strings and see if your string is in that collection. You can do it inline:
num = db.Table.Count(x => x.FavoriteSport == "Baseball" &&
new []{"Green","Red","Blue"}.Contains(x.FavoriteColor);
Worth noting that you can swap your Where
out for Count
directly
Upvotes: 3
Reputation: 34160
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;
Upvotes: 4
Reputation: 953
You can use a container of objects and use the Contains method. For example:
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 a profile to make sure that the generated SQL is using teh IN statement though.
Upvotes: 3