Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL Group by and Sum in Select

I need to convert that SQL Query into Linq:

SELECT
    SUM([ArticleAmount]) as amount
    ,[ArticleName]
FROM [DB].[dbo].[OrderedArticle]

group by articlename

order by amount desc

I tried the following code but I get an error at "a.ArticleName" that says a definition of "ArticleName" would be missing.

var sells = orderedArt
            .GroupBy(a => a.ArticleName)
            .Select(a => new {Amount = a.Sum(b => b.ArticleAmount),Name=a.ArticleName})
            .OrderByDescending(a=>a.Amount)
            .ToList();

Has someone of you and idea how to fix this?

Thanks for your help!

like image 272
Linus Avatar asked Dec 21 '12 10:12

Linus


1 Answers

You are getting this error because the Grouping doesn't return IEnumerable<OrderedArticle> but IEnumerable<IGrouping<string, OrderedArticle>>

You need to change your code to use a.Key:

var sells = orderedArt
    .GroupBy(a => a.ArticleName)
    .Select(a => new { Amount = a.Sum(b => b.ArticleAmount), Name = a.Key})
    .OrderByDescending(a => a.Amount)
    .ToList();
like image 96
Wouter de Kort Avatar answered Oct 05 '22 02:10

Wouter de Kort