我正在尝试读取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; }
}
答案 0 :(得分: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();