有没有更好的方法来编写这个LINQ查询?

时间:2010-05-24 05:44:52

标签: c# linq

是否有更好的简化方式来编写此查询。我的逻辑是 如果集合包含客户ID和国家/地区代码,请按客户ID升序查询ordey。如果CustIDs中没有包含ID,则按客户名称执行订单。有没有更好的方法来编写此查询?我并不熟悉复杂的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;
        }

1 个答案:

答案 0 :(得分:0)

可能是我从一开始就将“param”作为优化,并重写以下代码:

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