How to Sort a List of Dynamic Objects in C#
By FoxLearn 1/9/2025 3:32:15 AM 228
This flexibility bypasses static type checking, letting you perform operations on objects that behave as if they were strongly typed, but without needing to define specific model classes in advance.
Let’s consider an example where we have a collection of dynamic products represented as JSON, and we want to sort these products by their price:
[ { "productName": "Laptop", "price": 1200.50 }, { "productName": "Smartphone", "price": 799.99 }, { "productName": "Tablet", "price": 450.00 } ]
To sort this list by the price
property, we first need to deserialize the JSON data into a List<dynamic>
.
After that, we can use LINQ to sort the list.
List<dynamic> products = JsonConvert.DeserializeObject<List<dynamic>>(json); products = products.OrderBy(p => p.price).ToList(); foreach (var product in products) { Console.WriteLine(product); }
The output of the code would be:
{ "productName": "Tablet", "price": 450.00 } { "productName": "Smartphone", "price": 799.99 } { "productName": "Laptop", "price": 1200.50 }
In this example, the products are sorted by their price
in ascending order.
Notice that using dynamic
makes it easy to work with objects where the structure might not be predefined, while still giving you the ability to sort, filter, and manipulate the data.
- 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#