1

In c# I wanted to convert List to List and add new properties to object dynamically.

List<Customer> customerList; // has list of customer object
List<Properties> properties; // has { string:propertyname and string:value}

I wanted to add some properties dynamically to all customer object by iterating through the list similar to that of javascript in C# without loosing data in existing list of objects

I would get properties from other source.

How do I achieve this kind of behavior in C#.

for(Customer c in customerList)
{
  for(Property prop in properties)
   {
      c[prop.propertyName]=prop.value; // similar to javascript 
   }   
}

I would require this List to be accessed from my UI by making an API call and return the data in JSON format

Shashi
  • 1,112
  • 2
  • 17
  • 32
  • I could add public dynamic custom = new ExpandoObject(); to Customer and iterate customers and var cust = customers[i]; var exp = item.custom as IDictionary; exp[cust.propertyName] = cust.value ?? string.Empty; But is there a way where I could add properties to Customer instead of a property inside customer. – Shashi Mar 03 '16 at 00:34

1 Answers1

2

I wouldn't. I'd keep my list as a list of Customer and I would extend my Customer class to support access to a Dictionary of additional properties, accessible through an explicit indexer.

private Dictionary<string,Something>;
public Something this[string i]
{
    get { return InnerDictionary[i]; }
    set { InnerDictionary[i] = value; }
}
Community
  • 1
  • 1
spender
  • 117,338
  • 33
  • 229
  • 351
  • I would require this List to be accessed from my UI by making an API call and return the data in JSON format, so that's why I wanted it to be in Object format – Shashi Mar 02 '16 at 23:16