LINQ 上的简单查询
var q = from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points").**Value.ToString()**;
我想在执行此查询后获取 q 作为类型字符串。即使在保留额外的粗体线之后,这也给了我一些 IEnumerable 类型。
好吧,让我这样说吧。我想让上面的查询类似于下面的查询,而运行时不会抛出任何错误。
string q = from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points");
有什么帮助吗?
var q = from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points").**Value.ToString()**;
I would like to get q as a type string after executing this query. Even after keeping the extra bolded line this is giving me some IEnumerable type.
Well let me put it this way. I would like to make the above query something like below one without the runtime throwing any error.
string q = from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points");
Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Enumerable.FirstOrDefault 方法 (IEnumerable)
Enumerable.FirstOrDefault Method (IEnumerable)
LINQ总是返回一个可枚举的结果。要让它评估并返回一个结果,您可以使用
.First()
.FirstOrDefault()
.Single()
.SingleOrDefault()
根据您的要求。
LINQ will always return an enumerable result. To get it to evaluate and return one result you can use
.First()
.FirstOrDefault()
.Single()
.SingleOrDefault()
depending on your requirement.
即使结果包含单个记录,查询也会返回 IEnumerable。试试这个 -
或者如果你确定至少会有一条记录,那么就这样做 -
The query will return IEnumerable even if the result contains single record. Try this -
Or if you are sure that there will be atleast one record then do it like this -