Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't use LINQ methods on JObject?

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.

like image 365
ahdung Avatar asked May 10 '18 02:05

ahdung


1 Answers

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)
like image 145
mjwills Avatar answered Oct 04 '22 11:10

mjwills