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 != ""
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 != ""
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会推荐这个版本,因为我发现它更具可读性。
I would recommend this version as I find it more readable IMHO.
你可以做
you can do
Bala 进行空值检查,Talljoe 进行空字符串检查。但这两者兼而有之:
此外,检查字符串长度通常比针对空字符串进行相等性检查更好。
Bala's does the null check and Talljoe's does the empty string check. But this one does both:
Also, checking string length is usually better than equality check against an empty string.