所以我有查询:
var query =
from product in db.LUT_ProductInfos
where product.flavor == flavor && product.Container == container
select flavor;
返回 1 条记录(它应始终返回一条记录)。如何从结果中提取单个属性值?例如,如果它返回 1 条包含 3 列的记录,例如 firstName lastName phoneNumber,并且我想对每个值执行一些操作,例如
string fName = firstName
string lName = lastName
int pNumber = phoneNumber
在不涉及对象数据映射的情况下,从结果变量查询中提取这些值的最直接方法是什么
var query =
from product in db.LUT_ProductInfos
where product.flavor == flavor && product.Container == container
select new {product.Foo, product.flavor.Bar, ...};
var row = query.First(); // or Single(), FirstOrDefault(), SingleOrDefault()
string foo = row.Foo;
int bar = row.Bar;
...
这样做的好处是,SELECT
语句中仅包含所需的属性,并且没有隐藏的其他往返(延迟加载)。
var singleResult =
(from product in db.LUT_ProductInfos
where product.flavor == flavor && product.Container == container
select flavor).Single();
string fName = singleResult.firstName
string lName = singleResult.lastName
int pNumber = singleResult.phoneNumber
var row = db.LUT_ProductInfos
.SingleOrDefault(product => product.flavor == flavor && product.Container == container);
if (row != null)
{
string firstName = row.fName;
string lastName = row.lName;
string phone = row.pNumber;
}
最好和最简单的方法是像这样重新编码:
var query =
(from product in db.LUT_ProductInfos
where product.flavor == flavor && product.Container == container
select flavor).FirstOrDefault();
它将返回第一个匹配的记录。如果没有匹配的记录,它将重新生成 null 值,否则它将返回LUT_ProductInfos类的对象。 您也可以根据需要跳过记录,如下所示:
var query =
(from product in db.LUT_ProductInfos
where product.flavor == flavor && product.Container == container
select flavor).Skip(25).FirstOrDefault();