【问题标题】:Get all the books By Author - in Dictionary object(Dictionary<AuthorName, List<Book>>)按作者获取所有书籍 - 在 Dictionary 对象中(Dictionary<AuthorName, List<Book>>)
【发布时间】:2019-02-18 07:24:30
【问题描述】:

如何按作者获取所有书籍 - 在 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 的情况下对图书列表执行以下操作

【问题讨论】:

  • 有什么理由不想使用 LINQ?
  • Dictionary 对象在哪里?您希望结果为 1 吗?
  • 所以基本上,你想浏览书籍列表中的所有项目,检查你的字典中是否已经有书籍作者的条目并将书籍添加到书籍列表中特定于那个作者?您是否已经尝试过这样做?
  • 你为什么要使用字典?

标签: c# list dictionary


【解决方案1】:
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});
}

【讨论】:

  • AuthorName 属性有什么类型?
猜你喜欢
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2021-10-04
  • 1970-01-01
相关资源
最近更新 更多