简体   繁体   中英

Razor: adding dynamic values together

I have a set of values that are generated dynamically with a foreach loop, how can I add these into one value?

For instance, say I have a site where each node has a number associated with it. How can I add all these numbers together? So far I've figured it'd be something similar to the following, where the value of 'node.aNumberValue' is added to the next one, and so on:

@foreach (var x in nodes){

    var total = node.aNumberValue + node.aNumberValue (etc...);

    <p>@total</p>
} 

This is what you want, I think:

int total = 0;
@foreach (var x in nodes)
{
    total += x.aNumberValue;
}
<p>@total</p>

Or even better, just:

<p>@nodes.Sum(x => x.aNumberValue)</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM