vb.net Linq to SQL 中的求和和分组依据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/216513/
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
Sum and Group By in Linq to SQL?
提问by Herb Caudill
Just getting started with Linq to SQL so forgive the newbie question. I'm trying to reproduce the following (working) query in Linq to SQL (VB.NET):
刚刚开始使用 Linq to SQL,所以请原谅新手问题。我正在尝试在 Linq to SQL (VB.NET) 中重现以下(工作)查询:
Select
f.Title,
TotalArea = Sum(c.Area)
From Firms f
Left Join Concessions c on c.FirmID = f.FirmID
Group By f.Title
Order by Sum(c.Area) DESC
(A Firm has many Concessions; a Concession has an area in hectares. I want a list of Firms starting with the ones that have the greatest total area of all their concessions.)
(一个公司有很多特许经营区;一个特许经营区有一个以公顷为单位的面积。我想要一个公司列表,从所有特许经营区总面积最大的公司开始。)
I'm imagining something like this as the Linq to SQL equivalent (pseudo-code)
我想像这样的东西作为 Linq to SQL 等价物(伪代码)
From f As Firm In Db.Firms _
Order By f.Concessions.Sum(Area)
... but that's not right. Can anyone point me in the right direction?
……但这不对。任何人都可以指出我正确的方向吗?
回答by Herb Caudill
Answer
回答
Here's the correct Linq to SQL equivalent
这是正确的 Linq to SQL 等价物
From c In Concessions _
Join f In Firms on f.FirmID equals c.FirmID _
Group by f.Title _
Into TotalArea = sum(c.OfficialArea) _
Order by TotalArea Descending _
Select Title, TotalArea
Thanks to @CMS for pointing me to LinqPad- what a great tool. You just point it to your database and you're off and running. Not only are hundreds of samples included, but you can run them against included live databases. I was able to arrive at the above query in just a few minutes starting from the provided samples.
感谢@CMS 将我指向LinqPad- 多么棒的工具。您只需将其指向您的数据库,您就可以开始运行了。不仅包含数百个示例,而且您可以针对包含的实时数据库运行它们。从提供的示例开始,我能够在几分钟内完成上述查询。
回答by CMS
Hereyou can find many examples about using aggregate functions and grouping, additionally I recommend you very much LinqPad, it's a great tool to test your queries on the fly and it's very good way to learn LINQ, it comes preloaded with 200 examples.
在这里你可以找到很多关于使用聚合函数和分组的例子,另外我非常推荐你LinqPad,它是一个很好的工具来测试你的查询,它是学习 LINQ 的好方法,它预装了 200 个例子。