在这里,我需要在两个地方(如if和else condition)进行细微更改来重用linq查询。如何编写可重用的linq查询
if(some condition){
comms = (from s in config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>()
from c in s.Communications.Cast<CommunicationConfiguration>()
where s.CurrentBrand == true
select c).ToList().FirstOrDefault();
}
else{
comms = (from s in config.Subscriptions.Cast<CommunicationGroupConfiguration>()
from c in s.Communications.Cast<CommunicationConfiguration>()
where s.CurrentBrand == true
select c).ToList().FirstOrDefault();
}
这里
config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>()
在这两个查询中,仅此部分就发生了变化。如何有效地编写此查询。任何建议。
具有正确类型的占位符:
IQueryable<CommunicationGroupConfiguration> temp = null;
if(some condition)
{
temp = config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>();
}
else
{
temp = config.Subscriptions.Cast<CommunicationGroupConfiguration>();
}
comms =
(from s in temp
from c in s.Communications.Cast<CommunicationConfiguration>()
where s.CurrentBrand == true
select c).ToList().FirstOrDefault();
或者,您可以使用三元运算符(我认为这更干净):
comms =
(from s in (<some condition> ? config.PromoRegistration.Communications : config.Subscriptions).Cast<CommunicationGroupConfiguration>()
from c in s.Communications.Cast<CommunicationConfiguration>()
where s.CurrentBrand == true
select c).ToList().FirstOrDefault();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句