1

我正在尝试读取 XML 文件,但type of the expression in the select clause is incorrect. Type inference failed in the call to '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; }
}
4

1 回答 1

5

问题在于你的右括号——你在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();
于 2013-07-25T15:07:35.907 回答