tags:

views:

105

answers:

1

Hi Is there a better simplified way to write this query. My logic is if collection contains customer ids and countrycodes, do the query ordey by customer id ascending. If there are no contain id in CustIDs then do the order by customer name. Is there a better way to write this query? I'm not really familiar with complex lambdas.

 var custIdResult =  (from Customer c in CustomerCollection
      where (c.CustomerID.ToLower().Contains(param.ToLower()) &&
       (countryCodeFilters.Any(item => item.Equals(c.CountryCode))) )
                                  select c).ToList();

        if (custIdResult.Count > 0)
        {
            return from Customer c in custIdResult
               where ( c.CustomerName.ToLower().Contains(param.ToLower()) &&
                 countryCodeFilters.Any(item => item.Equals(c.CountryCode))) 
               orderby c.CustomerID ascending
               select c;
        }
        else
        {
            return from Customer c in CustomerCollection
               where (c.CustomerName.ToLower().Contains(param.ToLower()) &&
                  countryCodeFilters.Any(item => item.Equals(c.CountryCode)))
               orderby c.CustomerName descending
               select c;
        }
A: 

May be I'd low "param" as optimization at the very beginning and rewrite the following code like this:

param = param.ToLower();

var custIdResult = (from Customer c in CustomerCollection
                    where (c.CustomerID.ToLower().Contains(param) &&
                        (countryCodeFilters.Any(item => item.Equals(c.CountryCode))))
                    select c).ToList();

IEnumerable<Customer> source = custIdResult.Count > 0 ? custIdResult : CustomerCollection;

IEnumerable<Customer> q = from Customer ct in source
                            where
                                ct.CustomerName.ToLower().Contains(param) &&
                                countryCodeFilters.Any(item => item.Equals(ct.CountryCode))
                            select ct;                                                                  

if (custIdResult.Count > 0)
    return q.OrderBy(ct => ct.CustomerID);

return q.OrderByDescending(ct => ct.CustomerName);       
Andrew Florko
My brain was frozen and should have thought it this way:) Excellent. Thanks a lot.
Raj Aththanayake