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

标签 c# visual-studio-2010 linq-to-xml

我正在尝试读取一个 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/

相关文章:

c# - 无法使用 silverlight 类库加载 system.xml

visual-studio - VS2010 中缺少“属性页”选项卡

c# - 系统.Xml.XmlException : Unexpected end of file while parsing Name has occurred

.net - 在链式 XElement 轴方法中处理空引用的优雅方式

.net - 带有冒号的 xml 元素名称

c# - 将 Microsoft.Graph 与控制台应用程序结合使用

c# - WPF:MVP 与 MVVM

c# - 触发属性更改后的wpf按钮命令绑定(bind)

c# - 列表框控件在选择项目时抛出空异常

数组列表中的 C# 对象