Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to get max ID from json (Array) fromat below:

[
  {
    "Group": "1",
    "ID": 1,
    "Name": "User1",
    "Description": "Desc1"
  },
  {
    "Group": "2",
    "ID": 3,
    "Name": "User2",
    "Description": "Desc2"
  },
  {
    "Group": "3",
    "ID": 2,
    "Name": "User3",
    "Description": "Desc3"
  }
]


Also json (Object) format:

{
  "Group": "1",
  "ID": 1,
  "Name": "User1",
  "Description": "Desc1"
},
{
  "Group": "2",
  "ID": 3,
  "Name": "User2",
  "Description": "Desc2"
},
{
  "Group": "3",
  "ID": 2,
  "Name": "User3",
  "Description": "Desc3"
} 


Desired output:
3


What I have tried:

Many of them available for JavaScript code, Looking for C#
eg: Edit fiddle - JSFiddle - Code Playground[^]
Posted
Updated 6-Nov-21 3:49am
v5

The way you do it is not to manipulate the JSON directly: you read the JSON data into C~ objects - that's what Newtonsoft is there for - manipulate the C# objects, then cretae your summary data from that.

Manipulating the JSON directly is a PITA because it's text based and there are no "fixed points" to work from, including rows or even lines!
 
Share this answer
 
Hmmm... got it! this works for json that begin with [,
i think for some tweaks, this will also works for the json that begin with {
public int GetMaxIDLINQ()
{
  var userLists = JsonConvert.DeserializeObject<List<Author>>(json);
  int maxID = userLists.Max(x => x.ID);

  Console.WriteLine("Max ID :" + maxID.ToString());
  return maxID;
}


Or:
public int GetMaxID()
  {
    int maxID = JsonConvert.DeserializeObject<List<UserRoot>>(json)
                .Select(s => s.ID)
                .Max();

    Console.WriteLine("Max ID :" + maxID.ToString());
    return maxID;
  }


Also:
public int GetMaxID()
  {
    var userLists = JsonConvert.DeserializeObject<List<UserRoot>>(json);
    var maxID = userLists.OrderByDescending(i => i.ID).FirstOrDefault();

    Console.WriteLine("Max ID :" + maxID.ID.ToString());
    return maxID.ID;
  }


Hope that helps someone :)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900