您好我有一些我想运行的LINQ代码,但标准取决于我传递给函数的国家/地区变量是否为空。
因此,如果country变量为null,我想运行: -
var resorts = from r in db.WRESORT
where new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY)
如果国家/地区有值我要运行
var resorts = from r in db.WRESORT where r.COUNTRY == country
问题是,有没有办法将2语句合并为一个?
由于
答案 0 :(得分:5)
您可以使用检查country
是否有值然后使用country
创建数组,否则使用预定义列表创建
var arr = string.IsNullOrEmpty(country)
? new[] { "AUSTRIA", "FRANCE", "ITALY" }
: new[] { country };
var resorts = from r in db.WRESORT where arr.Contains(r.COUNTRY);
答案 1 :(得分:1)
可能是这个?:
var resorts = from r in db.WRESORT
where (country != null && r.COUNTRY == country) ||
(country == null && new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY))
答案 2 :(得分:1)
如果真的必须作为单个查询完成,那么:
var resorts = from r in db.WRESORT
where (
country == null ? new[] { "AUSTRIA", "FRANCE", "ITALY" } : new[]{country})
.Contains(r.COUNTRY);
但为什么不呢:
var resorts = country == null
? from r in db.WRESORT
where (new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY)
: from r in db.WRESORT where r.COUNTRY == country;
许多数据库和其他提供程序可以通过单个等式检查(=
)而不是包含(IN (…)
)做得更好,并且因为查询的类型将以相同的方式相同,这将工作,并生成相同类型的查询。代码分支在linq-y位之外发生了什么危害?
在这种情况下,您还可以提高可读性:
IQueryable<Resort> resorts;
if(country == null)
resorts = from r in db.WRESORT
where (new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY);
else
resorts = from r in db.WRESORT where r.COUNTRY == country;
因为IQueryable
的类型参数不是匿名的。如果您有类似.Select(r => new{r.COUNRY, r.Name})
的内容,那么这是不可能的。
答案 3 :(得分:-1)
交叉点:
var resorts =
from r in db.WRESORT
where new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY) && r.COUNTRY == country;
或
联合:
var resorts = from r in db.WRESORT
where new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY) || r.COUNTRY == country;