linq XML Sum IEnumerable <string> </string>

时间:2013-08-21 14:16:48

标签: c# xml linq

在以下查询中:

var foundNode3 = (from e in root.Descendants(df + "Inv")
            where e.Descendants(df + "Document").Any(item =>(string)item.Element(df + "InvS").Value == "N")
            select e.Element(df + "DocT").Element(df + "EndT").Value);

输出:23.98,12.34,24.4 ......

现在制作Sum()

var foundNode3 = (from e in root.Descendants(df + "Inv")
            where e.Descendants(df + "Document").Any(item =>(string)item.Element(df + "InvS").Value == "N")
            select double.Parse(e.Element(df + "DocT").Element(df + "EndT").Value)).Sum();

FormatException:输入错误的字符串

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:3)

听起来像double.Parse的输入是不可解析的。 http://msdn.microsoft.com/en-us/library/fd84bdyt.aspx Double.Parse(string s)在无效输入s上抛出FormatException。

答案 1 :(得分:0)

不知道怎么写它,但改变它可能会有所帮助:

var foundNode3 = root.Descendants(df + "Inv")
    .Where(e => e.Descendants(df + "Document")
                 .Any(item =>(string)item.Element(df + "InvS").Value == "N"))
    .Select(e =>
    {
        double value;
        string sValue = e.Element(df + "DocT").Element(df + "EndT").Value;
        if(double.TryParse(sValue, out value))
            return value;
        return 0;
    })
    .Sum();