Linq to SQL Group by和Sum in Select

时间:2012-12-21 10:54:49

标签: sql asp.net-mvc linq entity-framework

我需要将SQL查询转换为Linq:

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

group by articlename

order by amount desc

我尝试了以下代码,但是我在“a.ArticleName”上收到一条错误,指出“ArticleName”的定义会丢失。

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

你是否有人想知道如何解决这个问题?

感谢您的帮助!

1 个答案:

答案 0 :(得分:10)

您收到此错误,因为分组不会返回IEnumerable<OrderedArticle>,而是IEnumerable<IGrouping<string, OrderedArticle>>

您需要更改代码才能使用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();