zoukankan      html  css  js  c++  java
  • 【转帖】Linq

    http://stackoverflow.com/questions/250867/most-popular-group-by-in-linq

    Assuming a table of tags like the stackoverflow question tags:

    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:

    SELECT Tag, COUNT(Tag) FROM Tags GROUP BY Tag

    I've written some LINQ that works:

    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.

    So I then parse these anonymous types back into Tag objects:

    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
  • 相关阅读:
    CoreData
    转场动画
    java基础(8)
    java基础(7)
    java基础(6)
    java基础(5)
    java基础(4)
    java基础(3)
    java基础(2)
    java基础(1)
  • 原文地址:https://www.cnblogs.com/yanyuge/p/2748317.html
Copyright © 2011-2022 走看看