Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert IEnumerable<JToken> to JArray

Tags:

c#

linq

json.net

I'm using LINQ over a JArray to filter out the items based on a particular condition and want that result in a separate JArray.

JArray arrSameClass = (JArray) arrPupilEmailDetails.Where(joSameClass => joSameClass["uClassId"].ToString() == gidClassId.ToString());

But this is giving me an casting exception('unable to cast from IEnumerable<JToken> to JArray'). I've tried JArray.Parse() also. Any help ?

like image 654
izengod Avatar asked Jun 30 '17 05:06

izengod


People also ask

Is JToken a JArray?

JToken. Creates a JArray from an object. The object that will be used to create JArray. The JsonSerializer that will be used to read the object.

What is JArray C#?

JArray(Object[]) Initializes a new instance of the JArray class with the specified content. JArray(JArray) Initializes a new instance of the JArray class from another JArray object.


1 Answers

You can use the JArray(Object) constructor and pass it your IEnumerable<JToken> and the enumerable will be evaluated and used to construct the JArray:

var query = arrPupilEmailDetails.Where(joSameClass => joSameClass["uClassId"].ToString() == gidClassId.ToString());
var arrSameClass = new JArray(query);

Sample fiddle.

like image 166
dbc Avatar answered Oct 21 '22 20:10

dbc