Last day I have faced a problem when working with "Anonymous Type". In development procedure I have got result from a service which return object made of anonymous type. The problem arise when I need to access property of anonymous type. After made some r&d I have got the solution. Now share with you ....
Solution 1: (use reflection to retrieve the values of the following anonymous type)
var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
System.Type type = obj.GetType();
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);
// clientname return the result Ahsan
More generic solution:
public static T GetValueFromAnonymousType( object dataitem, string itemkey )
{
System.Type type = dataitem.GetType();
T itemvalue = (T)type.GetProperty(itemkey).GetValue(dataitem, null);
return itemvalue;
}
Example:
var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
string clientname = GetValueFromAnonymousType(obj, "ClientName");
Solution 2:
var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
string clientname = TypeUtils.GetValueFromAnonymousType(obj, "ClientName");
var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
Type t = obj.GetType();
//Then from that you look up a property:
PropertyInfo p = t.GetProperty("ClientName");
//Then from that you can get a value:
object v = p.GetValue(obj, null);
//This answer is long overdue for an update for C# 4:
dynamic d = obj;
object v = d.ClientName;
Hope that it may helpful for others.
Thanks
Solution 1: (use reflection to retrieve the values of the following anonymous type)
var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
System.Type type = obj.GetType();
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);
// clientname return the result Ahsan
More generic solution:
public static T GetValueFromAnonymousType
{
System.Type type = dataitem.GetType();
T itemvalue = (T)type.GetProperty(itemkey).GetValue(dataitem, null);
return itemvalue;
}
Example:
var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
string clientname = GetValueFromAnonymousType
Solution 2:
var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
string clientname = TypeUtils.GetValueFromAnonymousType
var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
Type t = obj.GetType();
//Then from that you look up a property:
PropertyInfo p = t.GetProperty("ClientName");
//Then from that you can get a value:
object v = p.GetValue(obj, null);
//This answer is long overdue for an update for C# 4:
dynamic d = obj;
object v = d.ClientName;
Hope that it may helpful for others.
Thanks