.net LINQ 中“最受欢迎”的 GROUP BY?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/250867/
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
"Most popular" GROUP BY in LINQ?
提问by tags2k
Assuming a table of tags like the stackoverflow question tags:
假设有一个标签表,如 stackoverflow 问题标签:
TagID (bigint), QuestionID (bigint), Tag (varchar)
TagID (bigint)、QuestionID (bigint)、Tag (varchar)
What is the most efficient way to get the 25 most used tags using LINQ? In SQL, a simple GROUP BY will do:
使用 LINQ 获取 25 个最常用标签的最有效方法是什么?在 SQL 中,一个简单的 GROUP BY 将执行以下操作:
SELECT Tag, COUNT(Tag) FROM Tags GROUP BY Tag
I've written some LINQ that works:
我写了一些有效的 LINQ:
var groups = from t in DataContext.Tags
group t by t.Tag into g
select new { Tag = g.Key, Frequency = g.Count() };
return groups.OrderByDescending(g => g.Frequency).Take(25);
Like, really? Isn't this mega-verbose? The sad thing is that I'm doing this to save a massive number of queries, as my Tag objects already contain a Frequency property that would otherwise need to check back with the database for every Tag if I actually used the property.
像,真的吗?这不是冗长的吗?可悲的是,我这样做是为了保存大量查询,因为我的 Tag 对象已经包含一个 Frequency 属性,否则如果我实际使用了该属性,则需要检查每个 Tag 的数据库。
So I then parse these anonymous types backinto Tag objects:
所以我然后将这些匿名类型解析回Tag 对象:
groups.OrderByDescending(g => g.Frequency).Take(25).ToList().ForEach(t => tags.Add(new Tag()
{
Tag = t.Tag,
Frequency = t.Frequency
}));
I'm a LINQ newbie, and this doesn't seem right. Please show me how it's really done.
我是 LINQ 新手,这似乎不对。请告诉我它是如何真正完成的。
采纳答案by James Curran
I'm pretty sure you've got it right. And, the SQL that LINQ generates and will send to your db will look just like the SQL you started with, so while you're doing a bit more typing, your database isn't doing any more work.
我很确定你做对了。而且,LINQ 生成并将发送到您的数据库的 SQL 看起来就像您开始使用的 SQL,因此当您输入更多内容时,您的数据库不会再做任何工作。
回答by GalacticCowboy
If you want Tag objects, why not create them directly from your Linq query?
如果您想要 Tag 对象,为什么不直接从您的 Linq 查询中创建它们呢?
var groups = from t in DataContext.Tags
group t by t.Tag into g
select new Tag() { Tag = g.Key, Frequency = g.Count() };
return groups.OrderByDescending(g => g.Frequency).Take(25);
回答by Amy B
If you use the verbose form of the syntax, your code will be verbose. Here's an alternative:
如果您使用语法的详细形式,您的代码将是冗长的。这是一个替代方案:
List<Tag> result =
db.Tags
.GroupBy(t => t.Tag)
.Select(g => new {Tag = g.Key, Frequency = g.Count()})
.OrderByDescending(t => t.Frequency)
.Take(25)
.ToList()
.Select(t => new Tag(){Tag = t.Tag, Frequency = t.Frequency})
.ToList();
回答by NetMage
I think you are also be unfair in that your SQL query does not do the same thing as your LINQ query - it doesn't return the top 25.
我认为您也不公平,因为您的 SQL 查询与您的 LINQ 查询执行的操作不同 - 它不返回前 25 个。

