将两个LINQ语句合并为一个语句



嗨,我有一些LINQ代码,我想运行,但标准取决于我传递给函数的国家变量是否为空。

因此,如果country变量为空,我想运行:-

  var resorts = from r in db.WRESORT
                      where new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY)

如果country有值,我想运行

  var resorts = from r in db.WRESORT where r.COUNTRY == country

问题是,有没有一种方法可以把这两个语句合并成一个?

谢谢

如果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);

可能是这样吗?:

var resorts = from r in db.WRESORT 
              where (country != null && r.COUNTRY == country) ||
                    (country == null && new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY))

如果真的必须作为单个查询完成,那么:

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 (…))做得更好,并且由于查询的类型无论哪种方式都是相同的,因此这将工作,并产生相同类型的查询。代码分支发生在链接位之外有什么害处?

在这种情况下,你也可以选择更容易读的:

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})之类的,那么这是不可能的。

交集:

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;

相关内容

  • 没有找到相关文章

最新更新