Linq to SQL Group by and Sum in Select

asp.net-mvc entity-framework linq sql

Question

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!

1
7
12/21/2012 10:54:49 AM

Accepted 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();
11
12/21/2012 11:08:50 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow