按词典获取所有作者的书-在Dictionary对象中(字典<authorname,列表<book =“” >>)

时间:2019-02-18 07:24:31

标签: c# list dictionary

如何按词典对象获取所有作者的书。 (字典>)

List<Book> authors = new List<Book>      
{  
   new Book{ AuthorName = " Chand", Book = "xyz", Price = 49 },      
   new Book{ AuthorName = "Neel ", Book = "abc", Price = 19 },      
   new Book{ AuthorName = "chetan", Book = "zxe", Price = 29 }      
};

在不使用LINQ的情况下,对书籍清单执行以下操作

1 个答案:

答案 0 :(得分:0)

var booksByAuthors = new Dictionary<string, List<Book>>();

foreach (var author in authors)
{
    if (booksByAuthors.ContainsKey(author.AuthorName))
        booksByAuthors[author.AuthorName].Add(author);
    else
        booksByAuthors.Add(author.AuthorName, new List<Book>{author});
}