Question

Here i need to reuse the linq query with a minor change in two places like if and else condition.How to write the reusable linq query

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

here

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

this part alone is changing in those two queries.How to write this query efficiently. Any suggestion.

Was it helpful?

Solution

Have a placeholder of the right type:

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

Or you could use the ternary operator (which is cleaner in my opinion):

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

OTHER TIPS

// 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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top