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!

3

1 Answer

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();
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest