[英]foreach var x in … with one result ASP.NET MVC RAZOR
I have this code: 我有以下代码:
foreach (var parent in @CurrentPage.AncestorsOrSelf().OrderBy("Level").Skip(2).Take(1))
{
...
}
The @CurrentPage.AncestorsOrSelf().OrderBy("Level").Skip(2).Take(1)
returns always one result, which is right. @CurrentPage.AncestorsOrSelf().OrderBy("Level").Skip(2).Take(1)
总是返回一个结果,这是正确的。 In this there is no sense to use foreach loop when the result is only one. 在这种情况下,当结果仅为一个时,就没有意义使用foreach循环。
How can i store the result from @CurrentPage.AncestorsOrSelf().OrderBy("Level").Skip(2).Take(1)
inside a variable? 如何将
@CurrentPage.AncestorsOrSelf().OrderBy("Level").Skip(2).Take(1)
在变量中?
You can call .First()
or .FirstOrDefault()
to get the actual object: 您可以调用
.First()
或.FirstOrDefault()
来获取实际对象:
var value = @CurrentPage.AncestorsOrSelf().OrderBy("Level").Skip(2).First();
The difference between them is that First()
will throw an exception if there are no items, while FirstOrDefault()
will return default(T)
(that is, null
for reference types and eg 0
for int
s etc). 它们之间的区别在于,如果没有项目,则
First()
将引发异常,而FirstOrDefault()
将返回default(T)
(即,对于引用类型为null
,对于int
等,例如为0
)。
Since you're extracting the first item, you don't need Take(1)
. 由于您要提取第一项,因此不需要
Take(1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.