MHogge
MHogge

Reputation: 5196

LINQ where query on a JToken

I'm new to LINQ query and I want to get 1 item (the one with id = 0) out of a JToken but I can't find out how this should be working.

I tried a lot a different way but this the code I tried first :

var statId0 = from stat in objectRankedStats where (int)stat["id"] == 0 select stat;

I've got this error :

Could not find an implementation of the query pattern for source type 'Newtonsoft.Json.Linq.JToken'. 'Where' not found. Are you missing a reference or a using directive for 'System.Linq'?

This is what looks like objectRankedStats :

{[  {
    "id": 40,
    "stats": 
    {
        "totalSessionsPlayed": 10,
        "totalSessionsLost": 8,
        "totalSessionsWon": 2,
    }  
},
{    
    "id": 6,
    "stats":
    {      
        "totalSessionsPlayed": 3,
        "totalSessionsLost": 2,
        "totalSessionsWon": 1, 
    }  
}

]}

I don't understand how the "quotes" handle backspaces

I declared objectRankedStats like this and I use it somewhere else in my code and it works.

var objectRankedStats = JObject.Parse(output)["champions"];

This is why I think it's null : enter image description here

I made a simplify version of the code I'm using on dotnetFiddle.com : https://dotnetfiddle.net/yS5cTk

Upvotes: 2

Views: 12160

Answers (1)

omikad
omikad

Reputation: 1009

This code works for me: https://dotnetfiddle.net/P95aNq

using System;
using System.Linq;
using Newtonsoft.Json.Linq;

namespace ConsoleApplication1
{
    static class Program
    {
        static void Main()
        {
            try
            {
                const string output = @"{""champions"": [  {
    ""id"": 40,
    ""stats"": 
    {
        ""totalSessionsPlayed"": 10,
        ""totalSessionsLost"": 8,
        ""totalSessionsWon"": 2,
    }  
},
{    
    ""id"": 6,
    ""stats"":
    {      
        ""totalSessionsPlayed"": 3,
        ""totalSessionsLost"": 2,
        ""totalSessionsWon"": 1, 
    }  
}
]}";

                var objectRankedStats = JObject.Parse(output)["champions"];

                var champ = objectRankedStats.FirstOrDefault(jt => (int)jt["id"] == 6);

                Console.WriteLine(champ);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

Upvotes: 3

Related Questions