C#如何循环json2csharp生成的类列表

时间:2018-09-08 11:36:16

标签: c# json loops arraylist

在使用http://json2csharp.com/之后,我得到了这种结构,并且试图遍历所有的Book,但是我不知道如何,我想有一种更好的方法像这样手动获取每个Book清单{ {1}}

简而言之,我想遍历每个BookStores[0].Prism.Books

List<Book>

1 个答案:

答案 0 :(得分:0)

接下来的实现如何?

public class Book
{
    public string name { get; set; }
    public int pages { get; set; }
    public double rating { get; set; }
    public bool available { get; set; }
}

public enum BookCategory
{
    Prism,
    Paragraphia
}

public class BookStore
{
    public Dictionary<BookCategory, List<Book>> Books { get; set; }
}

然后按如下所示使用它:

var bookStore = new BookStore();
bookStore.Books = new Dictionary<BookCategory, List<Book>>();

var paragrapiaBooks = new List<Book>();
paragrapiaBooks.Add(new Book{name = "Paragrapia book 1"});
paragrapiaBooks.Add(new Book{name = "Paragrapia book 2"});
bookStore.Books[BookCategory.Paragraphia] = paragrapiaBooks;

var prismBooks = new List<Book>();
prismBooks.Add(new Book{name = "Prism book 1"});
prismBooks.Add(new Book{name = "Prism book 2"});
bookStore.Books[BookCategory.Prism] = prismBooks;

foreach (var bookCategory in bookStore.Books)
{
    foreach (var book in bookCategory.Value)
    {
        Console.WriteLine(book.name);
    }
}
Console.ReadLine();

这样,您的实现也更加灵活,您不需要在需要新的图书类别时添加新的属性,而只需添加新的Enum值。除了Enum,还可以使用String

================================================ ======================

但是我认为以下解决方案更好,可以将属性category添加到Book类,因为它实际上是书籍的属性,而不是书籍的属性。即使将科幻小说放到装满菜谱的书架上,它仍将是科幻小说。

public class Book
{
    public string name { get; set; }
    public int pages { get; set; }
    public string category { get; set; }
    public double rating { get; set; }
    public bool available { get; set; }
}

public class BookStore
{
    public List<Book> Books { get; set; }
}

然后按如下所示使用它:

var bookStore = new BookStore();
bookStore.Books = new List<Book>();
bookStore.Books.Add(new Book { name = "Paragrapia book 1", category = "Paragrapia" });
bookStore.Books.Add(new Book { name = "Paragrapia book 2", category = "Paragrapia" });
bookStore.Books.Add(new Book { name = "Prism book 1", category = "Prism" });
bookStore.Books.Add(new Book { name = "Prism book 2", category = "Prism" });

Console.WriteLine("ONLY PRISM BOOKS:");
foreach (var book in bookStore.Books.Where(b => b.category == "Prism"))
{
    Console.WriteLine(book.name);
}

Console.WriteLine("\r\nALL BOOKS:");
foreach (var book in bookStore.Books)
{
    Console.WriteLine(book.name);
}
Console.ReadLine();