错误:无法将类型为“WhereSelectEnumerableIterator'2[System.Xml.Lin

本文关键字:System Lin Xml WhereSelectEnumerableIterator 类型 错误 | 更新日期: 2023-09-27 18:36:19

我有以下代码

    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>

错误:无法将类型为“WhereSelectEnumerableIterator'2[System.Xml.Lin

试试这个:

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

为什么不使用反序列化?

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

LINQ 表达式,如

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

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

  • 第一
  • 第一个或默认
  • 单或默认