【问题标题】:How to create a list using foreach - C#如何使用 foreach 创建一个列表 - C#
【发布时间】:2017-04-25 14:38:48
【问题描述】:

我有这门课:

public class JsonObj
{
    public string name { get; set; }
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<JsonObj> children { get; set; }
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public int? size { get; set; }

}

还有这个类和类的对象列表

public class MyObj
{
  public string Name {get; set;}
  public int Number {get; set;}
}

假设myList 有多个MyObj 对象。

现在我正在尝试创建一个大型 JsonObj,其子对象是 myList 成员。这就是我到目前为止所做的:

var root = new JsonObj
{
   name = "ROOT",
   children = new List<JsonObj>()
   {
     //I suppose I need to use foreach here, but I don't know how to do it.
   }
};

如何在此处使用该列表的循环创建对象?谢谢。

【问题讨论】:

  • 你不能foreach里面的构造函数实例化。在调用此代码之前创建列表并将列表分配给 children 属性。
  • 为什么需要foreach?你有什么收藏吗?
  • myList 的类型是什么? JsonObjMyObj 之间是什么关系?
  • @gobes myListMyObj 的类型,JsonObjMyObj 之间没有关系。我只需要将myObj 对象转换为JsonObj
  • "假设myList 有一个MyObj 的对象。" myList 不是 MyObj 实例的列表吗?

标签: c# list foreach


【解决方案1】:

你不能使用 foreach 一个初始化器。在 JsonObj 之前创建您的列表,并将其分配给孩子,或使用 LINQ。下面是一些例子:

var children = new List<JsonObj>();

foreach ( var child in myList )
{
    children.Add(new JsonObj
    {
        name = child.Name,
        size = child.Number
    });
}

var root = new JsonObj
{
   name = "ROOT",
   children = children
};

或 LINQ:

var root = new JsonObj
{
   name = "ROOT",
   children = myList.Select(child => new JsonObj
   {
       name = child.Name,
       size = child.Number
   }).ToList();
};

这是一个示例 dotnetfiddle here

【讨论】:

  • 这是一个获取他的孩子的功能。他没有解释孩子是从哪里来的,所以这是伪代码。
  • 你的意思是 myList 而不是 GetMyChildren() 吗?
  • 问题是不清楚 OP 在问什么。我的理解是他在JsonObjs 列表和MyObjs 列表之间遇到了映射问题...
  • 好的,如果 OP 的孩子在 myList 中,现在使用 myList 而不是 GetMyChildren()
  • 我照你说的做了。但它给出了这个错误:Argument 1: cannot convert from 'WebApplication2.Controllers.JsonObj' to 'int'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 2020-10-08
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
  • 2015-03-04
  • 2019-01-02
相关资源
最近更新 更多