0

这里的问题是每次我运行循环时都会重新创建类“obj”的实例,所以在循环结束时,我只有一组对象。它应该有几个。

foreach (var project in projectsDictionary)
{
    foreach (var season in seasonsDictionary)
    {
        foreach (var episode in episodesDictionary)
        {
            obj = new Parent
            {
                Title = project.Value, Link = "1", Children = new List<Parent>
                {
                    new Parent
                    {
                        Title = season.Value, Link = "1", Children = new List<Parent>
                        {
                            new Parent
                            {
                                Title = episode.Value, Link = "1", Children = null
                            }
                        }
                    }
                }
            };
        }
    }
}

var responseBody = JsonConvert.SerializeObject(obj);
return responseBody;

public class Parent
{
    public string Title
    {
        get;
        set;
    }

    public string Link
    {
        get;
        set;
    }

    public List<Parent> Children
    {
        get;
        set;
    }
}
4

1 回答 1

3

在第一个循环之外定义obj为一个列表。

var obj = new List<Parent>();

然后

obj.Add(new Parent(...));

于 2013-08-09T01:06:18.437 回答