Sorting JArray in C# with Newtonsoft.Json
By FoxLearn 1/9/2025 3:29:46 AM 156
Although you can't directly sort a JArray in C#, you can work around this limitation.
If your JArray consists of simple data types like numbers or strings, you can convert the JArray into a list, sort that list, and then convert it back into a JArray.
For example, let’s consider the following JSON array of numbers:
[5, 3, 8, 1, 7]
We want to sort this array in ascending order.
// Setting up the test data JArray jArray = new JArray(); jArray.Add(5); jArray.Add(3); jArray.Add(8); jArray.Add(1); jArray.Add(7); // Converting JArray to List and sorting List<int> numbers = jArray.ToObject<List<int>>(); numbers.Sort(); jArray = JArray.FromObject(numbers); // Output the sorted result foreach (var item in jArray) { Console.WriteLine(item); }
In this example:
- First, the
JArray
is converted to a strongly typed list of integers. - The list is then sorted in ascending order.
- Finally, the sorted list is converted back into a
JArray
.
Output:
1 3 5 7 8
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
How to secure ASP.NET Core with NWebSec
11/07/2024
Spica Admin Dashboard Template
11/18/2024