In today's article I will show a simple tutorial with example, how you can read data from a dynamic object and List<dynamic> object using c#.net in .net core. Here i am using .net 8 core in a console application. Now let's create a new console application and add value to dynamic object. After that we will check for List<dynamic>.
Read Data from dynamic Object
dynamic dynamicData;
dynamicData = new { Name = "Rakesh", Address = "R. Address" };
var name = dynamicData.GetType().GetProperty("Name");
if (name != null)
{
Console.WriteLine("Name: " + name.GetValue(dynamicData));
}
var address = dynamicData.GetType().GetProperty("Address");
if (address != null)
{
Console.WriteLine("Address: " + address.GetValue(dynamicData));
}
In above code I have taken a variable of dynamic type. After that I have added some value to the object. Now to get the value from the object I have demonstrated how we can get the value from dynamic object. So, to get data from dynamic object first we use
dynamicData.GetType().GetProperty("Name"); to get property and after validating property exists or not. If it does not exist on that case, we will get null and if property exists, we will use
name.GetValue(dynamicData) to get value. Now let's run the code and check the output.
Read Data from List<dynamic> Object
Here first we will take a list of class object and add some value in it. Please refer the below code.
List<EmployeeProperty> employees = new List<EmployeeProperty>()
{
new EmployeeProperty{ Id=1,Name="Rakesh", Address="R. Address"},
new EmployeeProperty{ Id=2,Name="Dhiraj", Address="D. Address"},
new EmployeeProperty{ Id=3,Name="Jonhn", Address="J. Address"},
new EmployeeProperty{ Id=4,Name="Mat", Address="M. Address"}
};
Now we will add the class list value to List<dynamic> object and shoe how we can read the value. Refer the below code.
List<dynamic> dynamicList = new List<dynamic>();
foreach (var employee in employees)
{
dynamicList.Add(new { employee.Id, employee.Name, employee.Address });
}
//Get List<dynamic> value
foreach (var item in dynamicList)
{
int emp_Id = 0;
string name_emp = string.Empty;
string address_emp = string.Empty;
var Id = item.GetType().GetProperty("Id");
if (Id != null)
{
emp_Id = Id.GetValue(item);
}
var Name = item.GetType().GetProperty("Name");
if (Name != null)
{
name_emp = Name.GetValue(item);
}
var Address = item.GetType().GetProperty("Address");
if (Address != null)
{
address_emp = Address.GetValue(item);
}
Console.WriteLine("Id: " + emp_Id + " ,Name: " + name_emp + " Address: " + address_emp);
}
Console.ReadLine();
In above code I have added the value in the List<dynamic>. After adding the value, I have each item property and value from dynamic list. and at the end I have displayed the values.