Linq to SQL Group and Sum in Select

I need to convert this SQL query to 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 the error "a.ArticleName" saying that the definition of "ArticleName" is 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(); 

Do any of you have an idea how to fix this?

Thank you for your help!

+4
source share
1 answer

You get this error because Grouping does not 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(); 
+6
source

All Articles