我在 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
。
最佳答案
在 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();"
关于c# - 如何在 microsoft.clearscript.v8 中的 jsondata 中使用 linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77684932/