有没有办法用JObject SelectTokens选择MAX值?

时间:2018-09-20 13:18:32

标签: c# json.net

让我们从以下JSON说起,我想选择价格最高的产品:

JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

例如:

IEnumerable<JToken> pricyProducts = o.SelectTokens("$..Products[?(MAX(@.Price))].Name");

有人知道如何获得最大值/最小值吗?

1 个答案:

答案 0 :(得分:2)

据我所知,JsonPath没有定义MAX函数,并且在Json.Net中尚未实现。您可以改用LINQ-to-JSON查询来获得所需的结果:

IEnumerable<JObject> products = o.SelectTokens("$..Products")
                                 .SelectMany(a => a.Children<JObject>());

decimal maxPrice = products.Max(p => (decimal)p["Price"]);

IEnumerable<JToken> pricyProducts = products.Where(p => (decimal)p["Price"] == maxPrice)
                                            .Select(p => p["Name"]);

提琴:https://dotnetfiddle.net/i4wkrv

相关问题