none
LINQ GroupBy RRS feed

  • Question

  • I am new to LINQ, and I am trying to return an IQueryable of type Region, and I wish to group by the Region Code, since it is repeated a lot of times in the table

    At the moment I have the following:-

           public static IQueryable<REGION> GetRegions()
            {
                IQueryable<REGION> _regions = from r in db.REGIONs
                                                    select r;

                return _regions;

            }

    How can I add a GROUPBY through LINQ?

    Thanks for your help and time


    http://www.johannmontfort.com
    Monday, June 1, 2009 3:06 PM

All replies

  • Grouping in LINQ works by creating a sequence of groupings.  So you end up with nested sequences of type IQueryable<IGrouping<>>:

    IQueryable<IGrouping<string,Region>> regionGroups =
       from r in db.Regions
       group r by r.RegionCode;

    Here's how to enumerate the result:

    foreach (var group in regionGroups)
    {
       Console.WriteLine (group.Key);   // The RegionCode
       foreach (Region r in group)
          Console.WriteLine (r.Name);    // Each region within the group
    }

    Note that this will round-trip SQL Server with each inner loop iteration. To avoid round-tripping, group on the client instead by calling AsEnumerable as follows:

    IEnumerable<IGrouping<string,Region>> regionGroups =
       from r in db.Regions.AsEnumerable()
       group r by r.RegionCode;


    If you want a flat list instead, use ordering instead of grouping:

    IQueryable<Region> regions = from r in db.Regions orderby r.RegionCode





    Write LINQ queries interactively - www.linqpad.net
    Monday, June 1, 2009 3:20 PM
    Answerer