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.
In
p => p.age > 25
,p.age
has typeNewtonsoft.Json.Linq.JValue
, making the comparison undefined (and, hence, nottrue
).The actual
JValue.Value
is anInt64
(long
) and it supports conversion byConvert
. Therefore, you can fix it by converting the value toint
(orlong
, if you want):Add:
And change the script line into: