views:

1475

answers:

3

I have this:

List<object> nodes = new List<object>(); 

nodes.Add(
new {
    Checked  = false,
    depth  = 1,
    id   = "div_" + d.Id
});

... and I'm wondering if I can then grab the "Checked" property of the anonymous object. I'm not sure if this is even possible. Tried doing this:

if (nodes.Any(n => n["Checked"] == false)) ... but it doesn't work.

Thanks

+16  A: 

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 */ });
Greg Beech
+11  A: 

If you're storing the object as type object, you need to use reflection. This is true of any object type, anonymous or otherwise. On an object o, you can get its type:

Type t = o.GetType();

Then from that you look up a property:

PropertyInfo p = t.GetProperty("Foo");

Then from that you can get a value:

object v = p.GetValue(o, null);
Daniel Earwicker
A: 

You could iterate over the anonymous type's properties using Reflection; see if there is a "Checked" property and if there is then get its value.

See this blog post: http://blogs.msdn.com/wriju/archive/2007/10/26/c-3-0-anonymous-type-and-net-reflection-hand-in-hand.aspx

So something like:

foreach(object o in nodes)
{
    Type t = o.GetType();

    PropertyInfo[] pi = t.GetProperties(); 

    foreach (PropertyInfo p in pi)
    {
        if (p.Name=="Checked" && !o.GetValue("Checked"))
            System.out.println("awesome!");
    }
}
lennyk