如何编写可重用linq查询

本文关键字:linq 查询 何编写 | 更新日期: 2023-09-27 18:00:27

这里我需要重用linq查询,在两个地方做一些小的更改,比如if和else条件。如何编写可重用的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>() 

仅这一部分就在这两个查询中发生了变化。如何高效地编写此查询。任何建议。

如何编写可重用linq查询

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

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