How to write reusable linq queries

Here I need to reuse the linq query with a slight change in two places, like if and else, for example. How to write a reused 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 per se changes in these two queries. How to write this query effectively. Any suggestion.

+4
source share
2 answers

Have a placeholder of the correct 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 can use the ternary operator (which, in my opinion, is cleaner):

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();
+5
source
// 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();
}
+1
source

Source: https://habr.com/ru/post/1538417/


All Articles