LINQ to Entities新手问题

时间:2011-04-10 00:27:03

标签: c# linq-to-entities

我不是一位经验丰富的C#程序员,目前我正在使用EF 3.5和LINQ做一些事情。

我有以下方法,我很确定它可以用更好/更短的方式编写。

感谢您的帮助!

  public List<CustOrder> GetOrders(string supplierId, string locationId)
    {
        using (var ctx = new OrderEntities())
        {
            if (!string.IsNullOrEmpty(locationId))
            {
                var result = (from order in ctx.CustOrder
                              where order.SupplierId == supplierId
                                 && order.LocationId == locationId
                              select order).ToList();
                return result;
            }
            else
            {
                var result = (from order in ctx.CustOrder
                              where order.SupplierId == supplierId
                                 && order.LocationId != ""
                              select order).ToList();
                return result;              
            }
        }
    }

我的错误: 在第二个linq查询中,应删除以下行:

&& order.LocationId != ""

4 个答案:

答案 0 :(得分:4)

我会推荐这个版本,因为我发现它更易读恕我直言。

public List<CustOrder> GetOrders(string supplierId, string locationId)
{
    using (var ctx = new OrderEntities())
    {
        var query = from order in ctx.CustOrder
                    where order.SupplierId == supplierId
                    select order;

        if (!string.IsNullOrEmpty(locationId))
        {
            query = query.Where(o => o.LocationId == locationId)
        }

        return query.ToList();
    }
}

答案 1 :(得分:0)

你可以做到

 public List<CustOrder> GetOrders(string supplierId, string locationId)
 {
        using (var ctx = new OrderEntities())
        {
             var result = (from order in ctx.CustOrder
                          where order.SupplierId == supplierId
                          && string.IsNullOrEmpty(locationId) ? true : order.LocationId == locationId
                                  select order).ToList();
             return result;
       }
 }

答案 2 :(得分:0)

var result = (from order in ctx.CustOrder
                          where order.SupplierId == supplierId
                             && (String.IsNullOrEmpty(locationId)
                               || order.LocationId == locationId)
                          select order).ToList();
            return result;

答案 3 :(得分:0)

Bala执行空检查,Talljoe执行空字符串检查。但是这个都做到了:

 public List<CustOrder> GetOrders(string supplierId, string locationId)
 {
        using (var ctx = new OrderEntities())
        {
             var result = (from order in ctx.CustOrder
                                  where order.SupplierId == supplierId
                                     && ((String.IsNullOrEmpty(locationId) && order.LocationId == locationId) || 
                                         order.LocationId.Length > 0)
                                  select order).ToList();
             return result;
       }
 }

此外,检查字符串长度通常比对空字符串的等式检查更好。