从循环项中获取总值

时间:2017-11-07 12:22:11

标签: c# asp.net-mvc

检查下面的代码。我正在循环以获取返回的XML响应的所有值。但我希望获得所有nofwatch变量的总值。如何添加它们以获得总价值?任何的想法?

foreach (var sri in searchResultItems)
{
    // Get all xml elements
    var childElements = sri.Elements();

    var nofwatch = childElements.FirstOrDefault(x => x.Name.LocalName == "listingInfo")
        .Elements().FirstOrDefault(x => x.Name.LocalName == "watchCount");

    //add items from xml data to EbayDataViewModel object
    items.Add(new EbayDataViewModel
    {
        TotalWatchers = nofwatch.Value //how can do + result of all nofwatch value?
    });

    ViewBag.TotalWatchers = TotalWatchers;
}

1 个答案:

答案 0 :(得分:3)

var totalValue = 0; //delcare the variable outside the foreach loop
foreach (var sri in searchResultItems)
{
    // Get all xml elements
    var childElements = sri.Elements();        
    var nofwatch = childElements.FirstOrDefault(x => x.Name.LocalName == "listingInfo")
        .Elements().FirstOrDefault(x => x.Name.LocalName == "watchCount");

    //now use += operator to add the result to the totalValue variable
    //totalValue += nofwatch.Value;

    //nofwatch.Value should be of type string and you would need to parse it as an integer first if that truely is the case
    var intValue = 0;
    if (int.TryParse(nofwatch.Value, out intValue) == false)
        continue;

    totalValue += intValue;
}

//outside of the foreach loop use totalValue to set the desired member
ViewBag.TotalWatchers = totalValue;