// The "myData" table contains two fields: name, value and type.
// The "myInfo" table contains two fields: type and value.
var myQuery = from x in myData
select new {
name = x.name,
value = x.value,
minValue = myInfo.Where(y => x.type == y.type).OrderBy(y => y.value).FirstOrDefault().value,
isOverMinValue = (myInfo.Where(y => x.type == y.type).OrderBy(y => y.value).FirstOrDefault().value) > x.value ? true : false
};
myInfo 表可能包含多个与 myData 中的类型相匹配的记录;我只想要最小值。然后我希望 isOverMinValue 字段指示 myData 中的值是否大于 myInfo 中找到的最小值。
在这个例子中,它有效,但正如您所看到的,我必须将整个子查询重复两次。这效率不高。我的替代方法是:
var myQuery = from x in myData
select new {
name = x.name,
value = x.value,
minValue = myInfo.Where(y => x.type == y.type).OrderBy(y => y.value).FirstOrDefault().value,
isOverMinValue = false
};
foreach (var myRec in myQuery)
{
if (myRec.minValue < x.Value) myRec.isOverMinValue = true;
}
但这不会起作用,因为匿名类型的属性似乎是只读的。
有没有更有效的方法来做到这一点?
(我不能进行连接,因为正如我所说,myInfo 可能包含多个条目,并且进行正常的 LINQ 连接最终会根据在 myInfo 中找到的匹配数量生成许多记录。)
最佳答案
你可以使用let
关键字:
var myQuery = from x in myData
let minvalue = myInfo.Where(y => x.type == y.type)
.OrderBy(y => y.value).FirstOrDefault().value
select new {
name = x.name,
value = x.value,
minValue = minvalue,
isOverMinValue = minvalue > x.value
};
顺便说一句,我不确定你是否正确使用了 >
符号。
关于C# 林奇 : Efficient way to set anonymous type property based on other values in query?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38152524/