如何在列表中找到作者,其中包含撰写大多数书籍的人员

时间:2015-04-14 15:32:08

标签: c# list collections

我有一个Book类,里面有成员titel和author。 我还有一本书籍清单,我想要找回写了大部分书籍的作者(大多数时候出现在列表中)。它在C#中。谢谢!

像这样:

书籍清单:

  

作者 - Titel

     

author1 - Peter Pan

     

author2 - 闪亮

     

author2 - IT

     

author3 - 动物农场

返回author2。

1 个答案:

答案 0 :(得分:2)

您可以使用LINQ

    internal class Book
    {
        public string Author;
        public string Title;
    }

    List<Book> listOfBooks = new List<Book>()
    {
        new Book() {Author = "author1", Title = "Peter Pan"},
        new Book() {Author = "author2", Title = "The Shining"},
        new Book() {Author = "author2", Title = "IT"},
        new Book() {Author = "author3", Title = "Animal Farm"},
    };

    var author = listOfBooks.GroupBy(x => x.Author)
        .OrderByDescending(g => g.Count())
        .Take(1)
        .Select(g => g.Key);