使用 LINQ 返回产品价格,函数中使用什么返回类型?
我刚刚开始使用 LINQ,我试图从数据库中选择并返回产品价格,如下所示:
public int GetPricePerKg(Product prod)
{
var result = from p in dc.Products
where p.pk_product_id == prod.pk_product_id
select p.product_price_kg;
return result;
}
这给了我错误:
无法将类型“
System.Linq.IQueryable
”隐式转换为“int
”
处理此问题的最佳方法是什么?我需要价格(在本例中是一个 int)并在另一个地方用它进行一些计算
I'm just getting started with LINQ and I'm trying to select and return a product price from database, like so:
public int GetPricePerKg(Product prod)
{
var result = from p in dc.Products
where p.pk_product_id == prod.pk_product_id
select p.product_price_kg;
return result;
}
This gives me the error:
Cannot implicitly convert type '
System.Linq.IQueryable<int?>
' to 'int
'
What's the best way to handle this? I need the price (which is an int in this case) and do some calculations with it in another place
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,您已经选择了一个查询 - 理论上可以匹配 0、1 或更多记录。在每种情况下你想做什么?另外,看起来
product_price_kg
是int?
- 如果它为空,你想做什么?您可能想要:
...但是如果没有完全匹配的产品或价格属性为空,则会引发异常。
如果您愿意,您仍然可以使用查询表达式 - 但对于您随后想要在末尾添加方法调用的简单情况,我倾向于不这样做。等效的查询表达式是:
或者,您可以使用带有谓词的
Single()
版本,如下所示:毫无疑问还有其他变体 - 它们都会做同样的事情 - 选择哪个您认为最具可读性的一个。
编辑:代替
Single
的其他选项有:First
(处理 1 个或更多)FirstOrDefault
(处理 0、1 或更多)SingleOrDefault
(处理 0 或 1)对于
OrDefault
版本,您需要弄清楚如果您没有匹配任何产品该怎么办。Well, you've selected a query - that could in theory match 0, 1 or more records. What do you want to do in each situation? Also, it looks like
product_price_kg
isint?
- what do you want to do if it's null?You might want:
... but that will throw an exception if either there isn't exactly one matching product or the price property is null.
You can still use a query expression if you want - but I tend not to for simple cases where you then want to add a method call at the end. The query expression equivalent is:
Alternatively, you can use the version of
Single()
which takes a predicate, like this:There are no doubt other variations - they'll all do the same thing - pick whichever one you find most readable.
EDIT: Other options instead of
Single
are:First
(cope with 1 or more)FirstOrDefault
(cope with 0, 1 or more)SingleOrDefault
(cope with 0 or 1)For the
OrDefault
versions you'd need to work out what to do if you didn't match any products.你需要做的(如果你只想恢复第一场比赛)
you need to do (if you only want the first match back)
约翰·斯基特和萨吉的答案都是正确的。这是另一种更符合您发布的代码的替代语法:
Both John Skeet and saj are right in their answers. Here's just another alternate syntax more in line with the code you posted:
您必须使用
FristOrDefault()
扩展方法you have to use
FristOrDefault()
extension method