15

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 ?

izengod
  • 1,116
  • 5
  • 17
  • 41

1 Answers1

21

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • Perfect! I have one question though, Is it a good way to pass an IEnumerable as a constructor param? I mean from performance perspective. – izengod Jun 30 '17 at 06:30
  • 1
    @izengod - At some point a `JArray` constructor is going to need to get called and items are going to need to get added. This does just that, so it's not prima facie nonperformant. Beyond that see https://ericlippert.com/2012/12/17/performance-rant/ – dbc Jun 30 '17 at 06:40
  • Problem I have with this solution is that if array is a child of a bigger object then creating a new `JArray` lose all the `Path` information. – MotKohn Nov 15 '17 at 20:51
  • 1
    The issue with that (preserving path) is that if you want to make the result of the query a JArray you have no choice but to change the parent to the new JArray. If you need the original path information then you must process as the original IEnumerable. – robs Nov 24 '20 at 06:10