【问题标题】:C# convert list<object> to list<dynamic> and add propertiesC# 将 list<object> 转换为 list<dynamic> 并添加属性
【发布时间】:2016-03-02 23:03:00
【问题描述】:

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

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 格式返回数据

【问题讨论】:

  • 我可以添加 public dynamic custom = new ExpandoObject();到客户并迭代客户和 var cust = customers[i]; var exp = item.custom as IDictionary; exp[cust.propertyName] = cust.value ??字符串。空;但是有没有办法可以向客户添加属性而不是客户内部的属性。

标签: c# .net c#-4.0 expandoobject


【解决方案1】:

我不会。我会将我的列表保留为Customer 的列表,并扩展我的Customer 类以支持访问Dictionary 的其他属性,可通过explicit indexer 访问。

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

【讨论】:

  • 我需要通过 API 调用从我的 UI 访问这个 List 并以 JSON 格式返回数据,所以这就是我希望它是 Object 格式的原因
猜你喜欢
  • 1970-01-01
  • 2021-05-20
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2021-03-29
相关资源
最近更新 更多