如何编写可重用的linq查询

Roo*_*ney 4 .net c# linq linq-to-entities

在这里我需要重用linq查询,在两个地方稍微改变,比如if和else condition.如何编写可重用的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();
}
Run Code Online (Sandbox Code Playgroud)

这里

config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>() 
Run Code Online (Sandbox Code Playgroud)

只有这一部分在这两个查询中发生了变化.如何有效地编写这个查询.任何建议.

i3a*_*non 5

有一个正确类型的占位符:

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();
Run Code Online (Sandbox Code Playgroud)

或者您可以使用三元运算符(在我看来更干净):

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();
Run Code Online (Sandbox Code Playgroud)