Creating Dynamic Arrays and Lists with Dynamic and ExpandoObject in C#
By FoxLearn 1/9/2025 3:01:32 AM 155
In this example, we demonstrate creating a dynamic list where the number of objects is not known in advance.
Let's assume we need to filter a list of people based on age criteria.
dynamic output = new List<dynamic>(); dynamic row1 = new ExpandoObject(); row1.Name = "Alice"; row1.Age = 25; output.Add(row1); dynamic row2 = new ExpandoObject(); row2.Name = "Bob"; row2.Age = 17; output.Add(row2);
Imagine you have a JSON object containing a list of people, and you need to extract only those whose age is 18 or older.
{ "people": [ { "name": "Alice", "age": 25 }, { "name": "Bob", "age": 17 }, { "name": "Charlie", "age": 30 } ] }
You can write the following C# code to process this data dynamically:
// Deserialize input JSON into a dynamic object dynamic input = JsonConvert.DeserializeObject(myJsonData); // Create an empty dynamic list for the output dynamic output = new List<dynamic>(); // Iterate through the people array and filter based on age foreach (var person in input.people) { if (person.age >= 18) { // Create a dynamic ExpandoObject for each person that meets the age criteria dynamic row = new ExpandoObject(); row.name = person.name; row.age = person.age; // Add the dynamic object to the output list output.Add(row); } } // Serialize the output list back to JSON string outputJson = JsonConvert.SerializeObject(output);
Output
[ { "name": "Alice", "age": 25 }, { "name": "Charlie", "age": 30 } ]
This example shows how you can filter data dynamically using C# ExpandoObject
and a List<dynamic>
, allowing you to handle variable data structures effectively.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Plus Admin Dashboard Template
11/18/2024
Dash UI HTML5 Admin Dashboard Template
11/18/2024
Material Dashboard Admin Template
11/17/2024