错误:无法将类型为'WhereSelectEnumerableIterator`2 [System.Xml.Linq.XElement,System.String]'的对象强制转换为'System.IConvertible'

时间:2013-10-22 09:48:40

标签: c# sql xml linq

我有以下代码

    var doc = XDocument.Load(@"export.xml");
    var companiesList = new Companies();

    var companies = (from c in doc.Descendants("Company")
                        select c).ToList();
    foreach (var xCompany in companies)
    {
        var company = new Company()
        {
            Name = (from x in xCompany.Descendants("Name") select x.Value).ToString(),
            Code = (from x in xCompany.Descendants("Code") select x.Value).ToString(),
            MaintenancePercentage =
                Convert.ToDouble(from x in xCompany.Descendants("MaintenancePercentage") select x.Value)
        };
        companiesList.AllCompanies.Add(company);
    }
    Console.WriteLine(companies);
    Console.ReadLine();
}

目前公司已经有3000家。我想把这些公司列入一个清单。

public class Companies
{
    public Companies()
    {
        AllCompanies = new List<Company>();
    }

    public List<Company> AllCompanies;
}

public class Company
{
    public string Name;
    public string Code;
    public double MaintenancePercentage;
    public double AverageSales;
    public double TotalSales;
    public double TotalMaintenanceFee;
    public List<Sales> Saleses;
}

在foreach语句中我得到错误说 错误:Unable to cast object of type 'WhereSelectEnumerableIterator 2 [System.Xml.Linq.XElement,System.String]'键入'System.IConvertible'。

知道我该怎么做才能让它发挥作用吗?

以下是示例xml代码

<Companies>
    <Company>
    <Name>Name1</Name><Code>11014</Code>    
    <MaintenancePercentage>15.9</MaintenancePercentage>
     <Sales>
       <Sale>
       <Code>19538</Code>
       <Title>ABC</Title>
       <Date>2009-04-29T00:00:00</Date>
       <Category>Category1</Category>
       <Amount>6543.39</Amount>
       </Sale>
       <Sale>
       <Code>19539</Code>
       <Title>xyz</Title>
       <Date>2009-04-30T00:00:00</Date>
       <Category>Category2</Category>
       <Amount>654.39</Amount>
       </Sale>
    </Sales>
    </Company>

    <Company>
    <Name>Name1</Name><Code>11014</Code>     
<MaintenancePercentage>15.9</MaintenancePercentage>
     <Sales>
       <Sale>
       <Code>19538</Code>
       <Title>ABC</Title>
       <Date>2009-04-29T00:00:00</Date>
       <Category>Category1</Category>
       <Amount>6543.39</Amount>
       </Sale>
       <Sale>
       <Code>19539</Code>
       <Title>xyz</Title>
       <Date>2009-04-30T00:00:00</Date>
       <Category>Category2</Category>
       <Amount>654.39</Amount>
       </Sale>
    </Sales>
    </Company>
</Companies>

2 个答案:

答案 0 :(得分:0)

试试这个:

Convert.ToDouble((from x in xCompany.Descendants("MaintenancePercentage") select x.Value).First())

为什么不使用反序列化?

要更正确地回答,有必要查看XML

答案 1 :(得分:0)

LINQ表达式

from x in xCompany.Descendants("Name") select x.Value

不返回单个对象,因此应用于ToString或Convert.ToDouble等结果函数并不完全正确 要获得单个值,请使用此扩展方法: