LINQ to Entities newbie question
I'm not an experienced C# programmer and currently I'm doing some stuff with EF 3.5 and LINQ.
I have the following method and I'm quite sure it can be written in a better / shorter way.
Thanks for the help!
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;
}
}
}
My mistake: In 2nd linq query, the following line should be removed:
&& order.LocationId != ""
I would recommend this version as I find it more readable IMHO.
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();
}
}
you can do
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 does the null check and Talljoe's does the empty string check. But this one does both:
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;
}
}
Also, checking string length is usually better than equality check against an empty string.
var result = (from order in ctx.CustOrder
where order.SupplierId == supplierId
&& (String.IsNullOrEmpty(locationId)
|| order.LocationId == locationId)
select order).ToList();
return result;
精彩评论