Why can't use LINQ methods on JObject?

风流意气都作罢 提交于 2019-12-07 06:42:37

问题


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

WHY? Thanks.


回答1:


JObject implements both IEnumerable<KeyValuePair<string, JToken>> and IEnumerable<JToken> (by inheriting from JContainer).

Thus you cannot use LINQ (e.g. Select) directly since it doesn't know which of the enumerables to 'extend'.

Thus you need to cast first:

((IEnumerable<KeyValuePair<string, JToken>>) jobj).Select(x => x)

or:

jobj.Cast<KeyValuePair<string, JToken>>().Select(x => x)

or as @Evk pointed out:

jobj.Select((KeyValuePair<string, JToken> x) => x)


来源:https://stackoverflow.com/questions/50264693/why-cant-use-linq-methods-on-jobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!