2

I have to add new properties in expando object in foreach loop but I am not able to see a way to do it. Here is the example:

var allProperties = new List { "Name", "Email", "Roles" }; allProperties.AddRange(metaDataModel.GetFormattedFolders());

dynamic expando = new ExpandoObject();
foreach (var s in allProperties)
{
    expando.s = string.Empty;
}

It consider 's' as a property instead of considering value of 's' as property name.

Thanks

Azhar Kiani
  • 323
  • 4
  • 11

1 Answers1

7
var expando = new ExpandoObject() as IDictionary<string, Object>;
foreach (var s in allProperties)
{
    expando.Add(s, string.Empty);
}
Damith
  • 62,401
  • 13
  • 102
  • 153
  • 1
    above does not work. It says:Cannot apply indexing with [] to an expression of type 'System.Dynamic.ExpandoObject' – Azhar Kiani Apr 14 '14 at 10:05
  • Thanks. It works. Not sure why we have to cast it into IDictionary object to acheive this? – Azhar Kiani Apr 14 '14 at 10:20
  • ExpandoObject is IDictionary underneath but you can't use indexing with`[]` or adding properties like we do with normal Collections. – Damith Apr 14 '14 at 10:27