How to Iterate Over the Properties of an Anonymous Object in C#

How do I iterate over the properties of an anonymous object in C#?

foreach(var prop in myVar.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
Console.WriteLine("Name: {0}, Value: {1}",prop.Name, prop.GetValue(myVar,null));
}

How to iterate through a list of anonymous objects?

You could use reflection to fetch properties of anonymous types:

var items = new List<object>();

var testObjectOne = new
{
Valueone = "test1",
ValueTwo = "test2",
ValueThree = "test3"
};
var testObjectTwo = new
{
Valueone = "test1",
ValueTwo = "test2",
ValueThree = "test3"
};
items.Add(testObjectOne);
items.Add(testObjectTwo);

foreach (var obj in items)
{
var val = obj.GetType()
.GetProperty("Valueone")
.GetValue(obj);
}

Iterate over object properties of an anonymous type list

You can get the properties of the type T with typeof(T).GetProperties(). This works with anonymous types as well.

Then you don't need to pull out the first item to inspect its properties, and you don't have to check for dataSet.Count > 0 (if you want to allow an empty spreadsheet).

Iterate over a collection of anonymous type in .NET

You still need to use the correct syntax for foreach which requires you to specify a type for the loop variable. Since you can't name it explicitly, you need to use var which infers the type.

foreach (var r in result)
{
Respone.Write(r.Book.Title, r.Book.ISBN, r.Category, r.Auhtor.Name);
}

Read properties from anonymous object

Instead of var use dynamic type for okResult. Thereafter, you can access your properties like: okResult.data and so on...

Update: As Daisy pointed out below, you will need InternalsVisibleTo because the generated anonymous type is internal, and the dynamic binder checks that.

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

How to get the properties from a dynamic (Anonymous Type) object using reflection?

Get the first item, cast it to object, and then you can get the properties:

object e = collection.FirstOrDefault();
var columns = e.GetType().GetProperties().Length;

Or just:

collection.FirstOrDefault().GetType().GetProperties().Length;


Related Topics



Leave a reply



Submit