在LINQ代码中创建新组时如何订购



我是Linq的新手,所以我正在努力正确地获取代码。我使用的是使用C#连接到Oracle数据库的LINQPAD 5。

我需要从表中显示每个出版商的书籍总数,并通过发布者ID订购。订单部分是我卡住的地方,因为我可以正确输出计数,但我无法正确订购。

这是我正在使用的表(省略了一些无关的列(。

    BOOK_ISBN    BOOK_TITLE                   BOOK_PUBID
    6541546      Birds and their cousins      4
    3214996      Outer worlds                 2
    3313545      Cats, Cats, Cats             3
    ...

我尝试了多种编写此书的方法,并在不同的地方订购了"订单"。我意识到,将"按订单"放在小组面前意味着基本上是无关紧要的,没有区别。我已经尝试在选择的新区域内按订单,但它不断提出错误,我无法使其工作。

这是我尝试的第一种方法,作为C#表达式。

from b in Books
.OrderByDescending(b => b.BookPubid)
group b.BookTitle by b.BookPubid into BooksbyPublisher 
select new
{
PublisherId     = BooksbyPublisher.Key,
Numberofbooks   = BooksbyPublisher.Count()
}

这是我尝试的第二种方法,作为C#语句。

var myQuery =
from b in Books
.OrderByDescending(b => b.BookPubid)
group b.BookTitle by b.BookPubid into BooksbyPublisher 
select new
{
PublisherId     = BooksbyPublisher.Key,
Numberofbooks   = BooksbyPublisher.Count(),
};
myQuery.Dump();

我希望输出为:

PublisherId     Numberofbooks
1               2
2               2
3               3
4               4
5               3

但它出现为:

PublisherId     Numberofbooks
1               2 
2               2 
4               4 
5               3 
3               3

,因此您有一个Books的序列,并且要将这些Books分组为由同一发布者发布的Books组(=具有相同的PublisherId(。从每组Books中,您要选择几个属性。

您是对的,为此,您将使用Enumerable的超载之一。

IQueryable<Book> books = ...  // your input collection of books
var result = books.GroupBy(book => book.PublisherId,   // make groups of books with same PublisherId
    // parameter ResultSelector: from every publisherId, and all books that have this
    // publisherId make one object:
    (publisherId, booksWithThisPublisherId) => new
    {
         // Select the properties you want,
         // in your example you want the PublisherId and the number of books of this Publisher
         PublisherId = publisherId,
         NumberOfBooks = booksWithThisPublisherId.Count(),
    })
    // and you want to sort them with ascending publisherId:
    .OrderBy(publisherWithNrOfBooks => publisherWithNumberOfBooks.PublisherId);

用文字:

获取书籍的输入集。与同一PublisherId制作一组书籍。从每个组中,制造一个新对象。该对象包含该组中所有书籍的常见发布。还计算该小组中的书籍数量。

最后,将每个"带有他的书籍数量的出版商"订购,并通过上升出版物订购。

简单的Comme Bonjour!

相关内容

最新更新