我相信有更好的方式来写这个,但我遇到了精神障碍。
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;
有没有更好的方法来编写OR
语句?我试过了:
x.FavoriteColor == "Green" || "Blue" || "Red"
但是编译器说Operator || cannot be applied to operands of type 'bool' and 'string'
感谢任何帮助。
答案 0 :(得分:9)
您可以使用数组/列表/ hashset的Contains方法。
var colors = new List<string> {"Green", "Red", "Blue" };
db.Table.Where(x => x.FavoriteSport == "Baseball" &&
(colors.Contains (x.FavoriteColor)).Count()
它将生成类似
的SQL查询SELECT ... WHERE FavoriteColor = 'Baseball' AND FavoriteColor in ("Green", "Red", "Blue")
我想补充一点,如果您使用存储在内存中的数据集,您应该记住,List Contains
需要O(N)迭代才能获得结果。因此,如果colors
包含大量元素,则应使用set HashSet而不是O(1)。
var colors = new HashSet<string> {"Green", "Red", "Blue", .... };
someDataSet.Where(x => x.FavoriteSport == "Baseball" &&
(colors.Contains (x.FavoriteColor)).Count()
您可以找到List-HashSet效果比较here
答案 1 :(得分:4)
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;
答案 2 :(得分:3)
您可以使用对象容器并使用Contains方法。例如:
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();
}
我会检查一个配置文件,以确保生成的SQL正在使用teh IN语句。
答案 3 :(得分:3)
几乎每个人都说过 - 你可以创建一个有效字符串的集合,看看你的字符串是否在该集合中。你可以内联:
num = db.Table.Count(x => x.FavoriteSport == "Baseball" &&
new []{"Green","Red","Blue"}.Contains(x.FavoriteColor);
值得注意的是,您可以直接将Where
换成Count