gpt4 book ai didi

c# - LINQ To XML 错误 : type of the expression in the select clause is incorrect. 调用 'Select' 时类型推断失败

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:25 24 4
gpt4 key购买 nike

我正在尝试读取一个 XML 文件,但是获取 select 子句中表达式的 type 是不正确的。由于以下查询而导致调用“Select”时类型推断失败错误:

List<Data> dogs = (from q in doc.Descendants("dog")
where (string)q.Attribute("name") == dogName
select new Data
{
name = q.Attribute("name").Value,
breed = q.Element("breed").Value,
sex = q.Element("sex").Value
}.ToList<Data>);

数据类:

public class Data
{
public string name { get; set; }
public string breed { get; set; }
public string sex { get; set; }
public List<string> dogs { get; set; }
}

最佳答案

问题在于您的右括号 - 您在 ToList() 调用的末尾得到了它,而您打算将它放在对象初始值设定项的末尾。此外,您实际上并没有调用该方法——您只是指定了一个方法组。最后,您可以让类型推断为您计算出类型参数:

List<Data> dogs = (from q in doc.Descendants("dog")
where (string)q.Attribute("name") == dogName
select new Data
{
name = q.Attribute("name").Value,
breed = q.Element("breed").Value,
sex = q.Element("sex").Value
}).ToList();

关于c# - LINQ To XML 错误 : type of the expression in the select clause is incorrect. 调用 'Select' 时类型推断失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17861740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com