我有一个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
-部分之间的查询中插入切换用例块。
您可以在多个语句中创建查询,因为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
部分中会有所不同,因此无法将它们全部分配给同一个变量。