8

我需要将该 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();

你们中有人知道如何解决这个问题吗?

谢谢你的帮助!

4

1 回答 1

16

您收到此错误是因为 Grouping 没有返回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();
于 2012-12-21T11:08:50.137 回答