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.