Is there a better way to write this LINQ query?
- by Raj Aththanayake
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;
}