How can I simply call the first returned value without a foreach
What am I missing here. I just want to pull the first one returned from row.detail in an MVC2 view, how would i do this without a foreach loop? This code currently works, but i just want the first one listed. Any idea.. I know this may be simple, but i am drawing a b开发者_StackOverflow社区lank.
if (Model.App != null)
{
foreach (var row in Model.App.Instructions)
{
<input type="hidden" value="<%= row.Detail %>" id="ixd" />
}
}
Use the First
extension method to get the first value out of a collection
Model.App.Instructions.First()
Note this will throw if the collection is empty. That can be worked around by using the FirstOrDefault
method that allows you to specify a default value should the collection be empty.
Seems everyone is going for LINQ's First(),
extension method, which is fine just as long as the collection isn't empty :) You might want to also consider FirstOrDefault()
and check for a null result.
A more obvious (to me at least) way of doing it without LINQ is simply to access the first element via it's index, so long as your type supports indexing. I.e. simply do this:
Model.App.Instructions[0]
Again, caveats on ensuring the collection is not empty.
Are you looking for
Model.App.Instructions.First()
LINQ should work.
Model.App.Instructions.First()
精彩评论