GroupBy into a List<> RRS feed

  • Question

  • Hello all, once again I'm in need of a bit of LINQ help.  I have a SQL query that looks like this:


    SELECT Model, COUNT(Model) as Total

    FROM [database].[table]

    GROUP BY Model

    ORDER BY Model


    I need to use LINQtoSQL to perform this query and store it into a List<Object>.  The list is of a type defined by a class that I have created.


    Here is the LINQ statement that I'm using:

    var models = (from model in db.BGInfoTables
                                  group model by model.Model into g
                                  select g);


    I don't really think it does what I want it to do though because when I put a where clause in there and look at the result set, it has four results, but should have had one with result with 4 items in it.


    Also, once I get the data, it won't let me cast it as the type needed for the List.  I'm not quite sure how to fix that either.


    Thanks in advance for any help.

    Monday, December 8, 2008 7:29 PM


  • Alright I figured it out!  It looks a bit crazy, but it works.  If interested, here it is:

     List<Models> lstModels = db.BGInfoTables
                                                    .GroupBy(m => m.Model)
                                                    .Select(g => new { DisplayName = g.Key, Count = g.Count()})
                                                    .OrderBy(g => g.DisplayName)
                                                    .Select(g => new Models(){DisplayName = g.DisplayName, Count = g.Count}).ToList();


    Monday, December 8, 2008 9:15 PM