C#LINQ:如何检索单个结果 [英] c# LINQ: how to retrieve a single result
问题描述
linq的新功能,
使用linq检索单个结果的最简单方法是什么?
whats the simplest way to retrieve a single result using linq?
示例,我的查询
var query =
from c in db.productInfo
where c.flavor == "Classic Coke" && c.container == "Can"
select c.co2Target;
它仅应返回一个带有双精度值的字段.我如何将其拉出查询?过去我曾经使用ExecuteScalar.我如何用linq做到这一点?我想保留其数据类型
it should only return a single field with a double value. how do i pull it out of query? In the past i had used ExecuteScalar. How do i do it with linq? I would like to preserve its data type
更新:
这就是我现在的位置.问题是在这里运行的测试查询返回的是4而不是3.75
Here's where I am now. The problem is that the test query im running here is returning 4 instead of 3.75
var query =
(from a in db.LUT_ProductInfos
where a.flavor == "Classic Coke" && a.Container == "Can"
select new { a.co2High }).Single();
double MyVar = query.co2High.Value;
推荐答案
我认为您的意思是返回一个值,而不是一个记录?您需要执行select new {}
如下:
I think you mean return one value, not one record? You would need to do select new {}
as follows:
var query =
from c in db.productInfo
where c.flavor == "Classic Coke" && c.container == "Can"
select new { c.co2Target };
然后,如果您只想检索单个记录,则:
Then if you only want to retrieve a single record as well as that:
var query =
(from c in db.productInfo
where c.flavor == "Classic Coke" && c.container == "Can"
select new { c.co2Target }).Single();
检索将按以下步骤进行:
Retrieval would be done as follows:
var query =
(from c in db.productInfo
where c.flavor == "Classic Coke" && c.container == "Can"
select new { c.co2Target }).Single();
double MyVar = query.co2Target;
这篇关于C#LINQ:如何检索单个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!