How to Sort a List of Dynamic Objects in C#
By FoxLearn 1/9/2025 3:32:15 AM 152
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#