The dynamic type in C# is a static type that bypasses static type checking. This makes it possible for you to work with objects like they were strongly typed, but without having to create named model classes beforehand.
Imagine that you have some dynamic data and you wish to sort it. In this example, I have a JSON array of users that I wish to sort after age:
[
{
"name": "Arthur Dent",
"age": 42
},
{
"name": "Ford Prefect",
"age": 1088
},
{
"name": "Zaphod Beeblebrox",
"age": 17
}
]
To sort this, I first convert the data from a JSON string to a List<dynamic>(), then I sort it. I use Newtonsoft.Json as converter:
List<dynamic> input = JsonConvert.DeserializeObject<List<dynamic>>(json);
input = input.OrderBy(a => a.age).ToList();
foreach (var inputItem in input)
{
Console.WriteLine(inputItem);
}
The output of the method is:
{
"name": "Zaphod Beeblebrox",
"age": 17
}
{
"name": "Arthur Dent",
"age": 42
}
{
"name": "Ford Prefect",
"age": 1088
}
That’s it. Happy coding.
MORE TO READ: