为什么不能在JObject上使用LINQ方法? [英] Why can't use LINQ methods on JObject?
本文介绍了为什么不能在JObject上使用LINQ方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Newtonsoft.Json.Linq.JObject
实现了IEnumerable<T>
,而不是显式实现,但是为什么不能这样做:
Newtonsoft.Json.Linq.JObject
implemented IEnumerable<T>
, and not explicit implementation, but why can't do this:
using System.Linq;
...
var jobj = new JObject();
var xxx = jobj.Select(x => x); //error
foreach(var x in jobj) { } //no error
为什么?谢谢.
推荐答案
JObject
同时实现IEnumerable<KeyValuePair<string, JToken>>
和IEnumerable<JToken>
(通过继承JContainer
).
因此您不能直接使用LINQ(例如Select
),因为它不知道要扩展哪些枚举.
Thus you cannot use LINQ (e.g. Select
) directly since it doesn't know which of the enumerables to 'extend'.
因此,您需要先投射:
((IEnumerable<KeyValuePair<string, JToken>>) jobj).Select(x => x)
或:
jobj.Cast<KeyValuePair<string, JToken>>().Select(x => x)
或@Evk指出:
jobj.Select((KeyValuePair<string, JToken> x) => x)
这篇关于为什么不能在JObject上使用LINQ方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文