tracer tong
tracer tong

Reputation: 553

Looping though a dictionary containing objects

I have the following loop over a dictionary type collection

foreach(KeyValuePair<Vector2, Object> entry in v_map.map_set)
{

}

I want to access the object properties, but the expected syntax doesn't work. E.G:

foreach(KeyValuePair<Vector2, Object> entry in v_map.map_set)
            {
                Object ob = entry.Value;
                ob.property;
            }

Fails because C# can't find the property wanted. So, how do I access the desired properties?

solution:

  foreach(KeyValuePair<Vector2, Object> entry in v_map.map_set)
            {
                if (entry.Value is warehouse)
                {
                    warehouse ob = (warehouse)entry.Value;

                }
            }

Upvotes: 4

Views: 210

Answers (5)

Geerten
Geerten

Reputation: 1057

If you know the type of the objects that are in the KeyValuePair, you can cast it to that type, and you will be able to find the properties you need.

And if you have several different objects stored, you can check which type it is by using is. Like so:

if(entry.Value is Foo)
{
   Foo lFoo = (Foo)entry.Value;
}
else if(entry.Value is Bar)
{
   Bar lBar = (Bar)entry.Value;
}

Upvotes: 2

Mike Perrenoud
Mike Perrenoud

Reputation: 67928

The problem is that you're using an object which isn't typed. So you're going to need to use reflection like this:

PropertyInfo pi = ob.GetType().GetProperty("PropertyName");
var val = pi.GetValue(ob, null);

Now, if the property isn't public then you'll need to employ something else like this:

PropertyInfo pi = ob.GetType().GetProperty("PropertyName", BindingFlags.Instance | BindingFlags.NonPublic);
var val = pi.GetValue(ob, null);

Now, if this is actually a field you're trying to get to, you're going to need to do something different even yet:

FieldInfo fi = ob.GetType().GetField("fieldName");
var val = fi.GetValue(ob);

GetProperty method

BindingFlags enumeration

GetField method

Upvotes: 0

Lee
Lee

Reputation: 144206

If you just need to access the values, and you know the expected type you can use

foreach(ExpectedType value in v_map.map_set.Values.OfType<ExpectedType>())
{
    var property = value.Property;
}

where Property is a property on ExpectedType.

Upvotes: 0

Daniel Kelley
Daniel Kelley

Reputation: 7747

You need to cast entry.Value to the type you need. The Object type itself isn't going to expose the properties you want.

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176956

You can make use of Refection to get the value of proerty of the object.

something like this

PropertyInfo info2 = object.GetType().GetProperty("prpertyname");
Object val = info2.GetValue(object, null);

Upvotes: 2

Related Questions