如何编写可重用的linq查询

时间:2014-04-28 13:54:27

标签: c# .net 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();
}

这里

config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>() 

这一部分单独改变了这两个查询。如何有效地编写此查询。任何建议。

2 个答案:

答案 0 :(得分: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();

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

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();

答案 1 :(得分:1)

// Or return IQueryable<CommunicationConfiguration> if you're using EF 
// or a provider that supports it
IEnumerable<CommunicationConfiguration> GetCommunicationConfiguration() 
{
    return someCondition 
      ? config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>().SelectMany(x => x.Communications).Cast<CommunicationConfiguration>()
      : config.Subscriptions.Cast<CommunicationGroupConfiguration>().SelectMany(x => x.CommunicationConfiguration).Cast<CommunicationConfiguration>();
}

public CommunicationConfiguration GetCurrentBrandCommunicationConfiguration() 
{
    return GetCommunicationConfiguration()
              .Where(x => x.CurrentBrand)
              .FirstOrDefault();
}