我正在学习LINQ并且正在尝试与select
子句相关的这个示例。
var q = from c in xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
.Select(n => new { SiteName = n.Element("name").Value});
以上查询给出了一个错误:
The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.
上述语法有什么问题?
除上述内容外,我必须转换selected
选项ToDictionary
。如何通过LINQ在同一个查询中完成?
我想到的第三个问题是关于编写相同查询的不同语法(e:下面的第二个方法编写示例)。首选的语法是什么?为什么?
from c in xmlDoc.Descendants
where c.Attriubute("technical").Value == "true"
select c.Element("site").Value;
答案 0 :(得分:3)
1。 你有混合lambda表达式与linq语法。从linq开始,以lambda表达式结束。试试这个
var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
.Select(n => new { SiteName = n.Element("name").Value});
或者你应该在linq中使用整个查询
var q = from c in xmlDoc.Descendants("site") where c.Attribute("technical").Value == "true"
select new { SiteName = c.Element("name").Value};
2。 只需在查询结尾使用ToDictionary
var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
.Select(n => new { SiteName = n.Element("name").Value,Key= n.Element("id").Value }).ToDictionary(n=>n.Key,l=>l.SiteName);
n => n.Key将为字典和l => l.siteName的键值。
3。 有两种创建此类查询的方法,一种是使用linq,另一种是使用使用lambda表达式作为参数的方法。两者都很简单,linq有点像SQL查询,而方法使用lambda更像是通过描述方法操作数据的简短手。我个人喜欢以方法为导向的方式,因为lambda更具有顺序可读性。