json.netjson.net

How to groupby JArray and show the max?


I have a JArray as below:

[
  {
    "group_pid": 1,
    "dataPool": 25000
  },
  {
    "group_pid": 0,
    "dataPool": 18750
  },
  {
    "group_pid": 1,
    "dataPool": 25000
  },
  {
    "group_pid": 1,
    "dataPool": 25000
  }
]

How to get the max value of the dataPool based on the group_pid?

from the example of the above JArray, I expect to get:

Expected result:

  [
      {
        "group_pid": 1,
        "dataPool": 25000
      },
      {
        "group_pid": 0,
        "dataPool": 18750
      }
   ]

I have tried the following, but I got compiler error CS0021, cannot apply indexing with []

JArray ja = (JArray)jaProjects.GroupBy(x => (long)x["group_pid"])
                .Select(x => (long)x["dataPool"]);

Solution

  • You’re only selecting "dataPool" directly without accounting for how you’ll pick the maximum value within each group_pid. Try using OrderByDescending and First or a nested Select to access each item in the grouped collections:

    using System;
    using System.Linq;
    using Newtonsoft.Json.Linq;
    
    public class Program
    {
        public static void Main()
        {
            string json = @"
            [
                { ""group_pid"": 1, ""dataPool"": 25000 },
                { ""group_pid"": 0, ""dataPool"": 18750 },
                { ""group_pid"": 1, ""dataPool"": 25000 },
                { ""group_pid"": 1, ""dataPool"": 25000 }
            ]";
            JArray jsonArray = JArray.Parse(json);
            var result = new JArray(
                jsonArray
                    .GroupBy(item => (int)item["group_pid"])
                    .Select(group => group
                        .OrderByDescending(item => (int)item["dataPool"])
                        .First())
            );
            Console.WriteLine(result.ToString());
        }
    }
    

    Output:

    [
      {
        "group_pid": 1,
        "dataPool": 25000
      },
      {
        "group_pid": 0,
        "dataPool": 18750
      }
    ]
    

    Try on dotnetfiddle.net