如何在microsoft.clearscript.v8中的jsondata中使用linq

问题描述 投票:0回答:1

我在 asp .net core mvc 中使用 microsoft.clearscript.v8, 在 Linq Where 条件在我的代码中不起作用,
这是我的 homecontroller.cs 代码

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();
}

我期望输出是使用 LinqWhere 条件的

id : 2, name : Jane, age : 30

c# linq v8 clearscript
1个回答
1
投票

p => p.age > 25
中,
p.age
具有类型
Newtonsoft.Json.Linq.JValue
,使得比较未定义(因此不是
true
)。

实际的

JValue.Value
是一个
Int64
long
)并且支持
Convert
的转换。因此,您可以通过将值转换为
int
(或
long
,如果需要的话)来修复它:

添加:

engine.AddHostType(typeof(Convert));

并将脚本行更改为:

@"var result = PersonList.Where(new Pred(p => Convert.ToInt32(p.age) > 25)).ToList();"
© www.soinside.com 2019 - 2024. All rights reserved.