如何用LINQ求值的和

时间:2021-12-17 12:03:13

My xml file looks like this

我的xml文件是这样的

<xxx>
    <fff>1</fff>
</xxx>
<xxx>
    <fff>1</fff>
</xxx>

And I want to find the sum of values in nodes . I was trying like this:

我想求节点上的值的和。我是这样尝试的:

var sum = from c in el.Elements()
         select new {I don't know what to write here}

and then iterating through sum, but I want to do it in one query.

然后遍历sum,我想在一个查询中进行。

How the query will be look like?

查询是什么样子的?

3 个解决方案

#1


5  

Maybe something like this?

也许是这样的?

int sum = root.Descendants("fff").Sum(e => (int) e);

#2


3  

I think it will be more like this:

我想会更像这样:

int sum = root.Descendants("fff").Sum(e => int.Parse(e.Value));

#3


0  

For the exception case you need to use TryParse not Parse, e.g.

对于异常情况,您需要使用TryParse而不是Parse。

int sum = el.Descendants("fff").Sum (e => 
    { 
        int v;
        return int.TryParse(e.Value, out v) ? v : 0;
    });

#1


5  

Maybe something like this?

也许是这样的?

int sum = root.Descendants("fff").Sum(e => (int) e);

#2


3  

I think it will be more like this:

我想会更像这样:

int sum = root.Descendants("fff").Sum(e => int.Parse(e.Value));

#3


0  

For the exception case you need to use TryParse not Parse, e.g.

对于异常情况,您需要使用TryParse而不是Parse。

int sum = el.Descendants("fff").Sum (e => 
    { 
        int v;
        return int.TryParse(e.Value, out v) ? v : 0;
    });