Oorderby after groupby LINQ C# (without lambda)

I am currently doing a groupby on a table as below:

var Query2 =
from b in Books
group b.BookPubid by b.BookPubid into g
select new
{
    PublisherID = g.Key,
    TotalBooks = g.Count()

};

What I want to do is orderby PublisherId. Any suggesetions please? I tried looking at posts but couldnt really find one that uses above format instead of using => to iterate through each rows..

Ty

2 answers

  • answered 2019-05-18 07:03 Sweeper

    Think about what happens after you grouped by BookPubid. You now have an enumerable of IGrouping<int, Book> called g, assuming the publisher ID is an int. Notice how the publisher ID becomes the Key of each IGrouping. Therefore, you should order by g.Key:

    var Query2 =
    from b in list
    group b.BookPubid by b.BookPubid into g
    orderby g.Key
    select new
    {
        PublisherID = g.Key,
        TotalBooks = g.Count()
    };
    

  • answered 2019-05-18 07:03 Shyam Vemula

    Try this.

    var Query2 =
    from b in Books
    orderby b.BookPubid
    group b.BookPubid by b.BookPubid into g
    select new
    {
       PublisherID = g.Key,
       TotalBooks = g.Count()
    };