LINQ到实体新手问题

本文关键字:问题 新手 实体 LINQ | 更新日期: 2023-09-27 17:49:40

我不是一个有经验的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 != ""

LINQ到实体新手问题

我推荐这个版本,因为我觉得它更具可读性。

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

你可以做

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

Bala's进行空检查,Talljoe's进行空字符串检查。但这一个兼有:

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

同样,检查字符串长度通常比检查空字符串的相等性要好。

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