C# 将列表<对象>转换为列表<动态>并添加属性

本文关键字:列表 添加 属性 动态 对象 转换 | 更新日期: 2023-09-27 18:37:04

在 c# 中,我想将列表转换为列表并动态向对象添加新属性。

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

我想通过遍历类似于 C# 中的 javascript 的列表来动态地向所有客户对象添加一些属性,而不会丢失现有对象列表中的数据

我会从其他来源获得属性。

如何在 C# 中实现这种行为。

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

我需要通过进行 API 调用从我的 UI 访问此列表并以 JSON 格式返回数据

C# 将列表<对象>转换为列表<动态>并添加属性

我不会。我将列表保留为Customer列表,并将扩展Customer类以支持访问Dictionary其他属性,这些属性可通过显式索引器访问。

private Dictionary<string,Something>;
public Something this[string i]
{
    get { return InnerDictionary[i]; }
    set { InnerDictionary[i] = value; }
}