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

1
  • I could add public dynamic custom = new ExpandoObject(); to Customer and iterate customers and var cust = customers[i]; var exp = item.custom as IDictionary<String, object>; 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. Commented Mar 3, 2016 at 0:34

1 Answer 1

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.