我正在运行带有连接的LINQ查询。我在变量var query = from r in db.Roughs
join a in db.Assorts on r.ROUGHNO equals a.RFNO into ra
from a in ra.DefaultIfEmpty()
where r.ROUGHNO == id.ToString()
select new { AVAILABLECARET=r.CARET - a.CARET };
中存储两列的减法。
AVAILABLECARET
如何在变量中获得var AVAILABLECARET= from r in db.Roughs
join a in db.Assorts on r.ROUGHNO equals a.RFNO into ra
from a in ra.DefaultIfEmpty()
where r.ROUGHNO == id.ToString()
select new { AVAILABLECARET=r.CARET - a.CARET }.AVAILABLECARET;
?
更新
我能够通过以下方式弄明白
#pragma once
const size_t X = 0; //No Ambiguity, size_t declared in vcruntime.h
#include <string>
const size_t Y = 0; //Ambiguity, size_t declared in vcruntime.h and xlocinfo.h
答案 0 :(得分:1)
要获得单一价值,你必须这样做
decimal values = (from r in db.Roughs
join a in db.Assorts on r.ROUGHNO equals a.RFNO into ra
from a in ra.DefaultIfEmpty()
where r.ROUGHNO == id.ToString()
select (r.CARET - a.CARET )).Sum();
或者如果你想获得最高
decimal? val = (from r in db.Roughs
join a in db.Assorts on r.ROUGHNO equals a.RFNO into ra
from a in ra.DefaultIfEmpty()
where r.ROUGHNO == id.ToString()
select (r.CARET - a.CARET )).FirstOrDefault();
在您的查询中尝试ToList()
您将获得结果,并在此处使用IEnumerable<T>
作为变量类型T替换您期望的类型。
根据您的查询,您正在进行外连接,那么您应该尝试,假设十进制类型
IEnumerable<decimal> values = (from r in db.Roughs
join a in db.Assorts on r.ROUGHNO equals a.RFNO into ra
from a in ra.DefaultIfEmpty()
where r.ROUGHNO == id.ToString()
select (r.CARET - (a == null ? 0 : a.CARET))).ToList();
如果变量的类型是int
那么,它将如下所示
IEnumerable<int> values = (from r in db.Roughs
join a in db.Assorts on r.ROUGHNO equals a.RFNO into ra
from a in ra.DefaultIfEmpty()
where r.ROUGHNO == id.ToString()
select (r.CARET - a.CARET )).ToList();
所以我指出你所期望的任何类型都可以替换为int,如果你的十进制数小于IEnumerable<deimal>
Linq查询返回给你IEnumerable<T>
这里T替换为你是expcetion的类型,你需要ToList()
函数来获得结果并立即执行你的查询。
答案 1 :(得分:1)
您可以使用.ToList()
,然后最好不要创建匿名对象,因此请删除new {...}
部分:
var values =
(from r in db.Roughs
join a in db.Assorts on r.ROUGHNO equals a.RFNO into ra
from a in ra.DefaultIfEmpty()
where r.ROUGHNO == id.ToString()
select r.CARET - a.CARET
).ToList();
这会为您提供List<someNumericType>
,具体取决于您的CARET字段可能具有的类型。
如果您只需要第一个值(如果没有,则为null):
var value =
(from r in db.Roughs
join a in db.Assorts on r.ROUGHNO equals a.RFNO into ra
from a in ra.DefaultIfEmpty()
where r.ROUGHNO == id.ToString()
select r.CARET - a.CARET
).FirstOrDefault();
这会产生Nullable<someNumericType>
,具体取决于您的CARET字段可能具有的任何类型。
答案 2 :(得分:0)
您可以在这样的变量中指定值。在查询后放置此行。
var value =query.FirstOrDefault();