我有这堂课:
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.
}
};
如何在此处使用该列表的循环创建对象?感谢。
答案 0 :(得分:11)
您无法使用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的示例。