Search code examples
c#linqv8clearscript

How to use linq in jsondata in microsoft.clearscript.v8


I am use microsoft.clearscript.v8 in asp .net core mvc, in the Linq Where condition is not work in my code,
this is my homecontroller.cs code

public IActionResult Index()
{
    using (var engine = new V8ScriptEngine())
    {
        string json = @"
        [
            { ""id"": 1, ""name"": ""John"", ""age"": 25 },
            { ""id"": 2, ""name"": ""Jane"", ""age"": 30 }      
        ]";

        // Parse JSON as JArray
        var jsonArray = JArray.Parse(json);

        // Use ClearScript to filter the data
        engine.Script.PersonList = jsonArray.ToObject<List<dynamic>>();
        engine.AddHostType(typeof(Enumerable));
        engine.AddHostType("Pred", typeof(Func<dynamic, bool>));

        engine.Execute(@"var result = PersonList.Where(new Pred(p => p.age > 25)).ToList();");

        // Retrieve the result from the script engine
        List<dynamic> filteredList = engine.Script.result;

        // Print filtered results
        foreach (var person in filteredList)
        {
            Console.WriteLine($"Id: {person.id}, Name: {person.name}, Age: {person.age}");
        }
    }
    return view();
}

I expecting the Output is the id : 2, name : Jane, age : 30 with using Linq Where condition.


Solution

  • In p => p.age > 25, p.age has type Newtonsoft.Json.Linq.JValue, making the comparison undefined (and, hence, not true).

    The actual JValue.Value is an Int64 (long) and it supports conversion by Convert. Therefore, you can fix it by converting the value to int (or long, if you want):

    Add:

    engine.AddHostType(typeof(Convert));
    

    And change the script line into:

    @"var result = PersonList.Where(new Pred(p => Convert.ToInt32(p.age) > 25)).ToList();"