Linq to SQL Group by 和 Sum in Select
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13988800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq to SQL Group by and Sum in Select
提问by Linus
I need to convert that SQL Query into Linq:
我需要将该 SQL 查询转换为 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.
我尝试了以下代码,但在“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();
Has someone of you and idea how to fix this?
你们中有人知道如何解决这个问题吗?
Thanks for your help!
谢谢你的帮助!
回答by Wouter de Kort
You are getting this error because the Grouping doesn't return IEnumerable<OrderedArticle>
but IEnumerable<IGrouping<string, OrderedArticle>>
您收到此错误是因为分组没有返回IEnumerable<OrderedArticle>
但IEnumerable<IGrouping<string, OrderedArticle>>
You need to change your code to use a.Key
:
您需要更改代码才能使用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();