我有一个LINQ查询,如下所示:
var query = from produkt in Entity.ProduktCollection.produktCollection
let p = produkt as Entity.Produkt
from version in p.version
let v = version as Entity.Version
from customer in v.customerCollection
let c = customer as Entity.Customer
from fehler in v.fehlerCollection
let f = fehler as Entity.Fehler
where f.id == GetGuid();
select p;
但我真正需要的是一种使f
加上其属性以及p
变量的方法,因此我可能会将它们更改为其他所有可能的组合,例如:
where c.name == "frank"
select f;
或
where p.id == GetGuid2()
select c;
有没有办法实现这个目标?据我所知,无法在from
/ let
- 部分和where
/ select
部分之间的查询中插入switch-case块。
答案 0 :(得分:6)
您可以在多个语句中创建查询,因为LINQ查询执行是延迟的。它适用于不同的Where
语句情况:
var querySource = from produkt in Entity.ProduktCollection.produktCollection
let p = produkt as Entity.Produkt
from version in p.version
let v = version as Entity.Version
from customer in v.customerCollection
let c = customer as Entity.Customer
from fehler in v.fehlerCollection
let f = fehler as Entity.Fehler
select new { p, v, c, f };
if(/* first condition */)
{
querySource = querySource.Where(x => x.f.id == GetGuid());
}
else if(/* second condition */)
{
querySource = querySource.Where(x => x.p.id = 34);
}
var query = querySource.Select(x => x.p);
您也可以将Select
部分设置为条件,但由于IEnumerable<T>
部分中返回的T
不同,您将无法将它们全部分配给同一个变量。