我有这门课:
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; }
}
Run Code Online (Sandbox Code Playgroud)
还有这个类和类'对象的列表
public class MyObj
{
public string Name {get; set;}
public int Number {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
并且假设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.
}
};
Run Code Online (Sandbox Code Playgroud)
如何在此处使用该列表的循环创建对象?谢谢.
Fra*_*erZ 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
};
Run Code Online (Sandbox Code Playgroud)
或LINQ:
var root = new JsonObj
{
name = "ROOT",
children = myList.Select(child => new JsonObj
{
name = child.Name,
size = child.Number
}).ToList();
};
Run Code Online (Sandbox Code Playgroud)
下面是dotnetfiddle的例子在这里.
| 归档时间: |
|
| 查看次数: |
4185 次 |
| 最近记录: |