Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check to see if a property exists within a C# Expando class

I would like to see if a property exist in a C# Expando Class.

much like the hasattr function in python. I would like the c# equalant for hasattr.

something like this...

if (HasAttr(model, "Id"))
{
  # Do something with model.Id
}
like image 560
eiu165 Avatar asked Aug 20 '12 20:08

eiu165


People also ask

How do you check if a list of object contains a value?

You can use the Enumerable. Where extension method: var matches = myList. Where(p => p.Name == nameToExtract);

How do I know if I have expandoObject property?

You can use this to see if a member is defined: var expandoObject = ...; if(((IDictionary<String, object>)expandoObject). ContainsKey("SomeMember")) { // expandoObject. SomeMember exists. }


1 Answers

Try:

dynamic yourExpando = new ExpandoObject();
if (((IDictionary<string, Object>)yourExpando).ContainsKey("Id"))
{
    //Has property...
}

An ExpandoObject explicitly implements IDictionary<string, Object>, where the Key is a property name. You can then check to see if the dictionary contains the key. You can also write a little helper method if you need to do this kind of check often:

private static bool HasAttr(ExpandoObject expando, string key)
{
    return ((IDictionary<string, Object>) expando).ContainsKey(key);
}

And use it like so:

if (HasAttr(yourExpando, "Id"))
{
    //Has property...
}
like image 75
vcsjones Avatar answered Oct 23 '22 03:10

vcsjones