Is there a better way to write this LINQ query?
Posted
by Raj Aththanayake
on Stack Overflow
See other posts from Stack Overflow
or by Raj Aththanayake
Published on 2010-05-24T05:44:52Z
Indexed on
2010/05/24
6:01 UTC
Read the original article
Hit count: 272
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;
}
© Stack Overflow or respective owner