GroupBy ... How to solve this problem? RRS feed

  • Question

  • Hello,

    I have the following lambda expression:
          return _context.Regions.SelectMany(r => r.Centers, (r, l) => new { r.Id, r.Name, Centers = r.Centers.Where(c => c.Open == true) })
    .Where(o => o.Centers.Count() > 0)
    .OrderBy(o => o.Name)
    .Select(o => new Models.Region {
    Id = o.Id,
    Name = o.Name
    Basically I am trying to get all regions which are related to at least one center.
    But I want to group by Region ... And not have two regions if it is related with two centers.

    I tried to add .GroupBy(o => o.Id) after the Where but then I got the error:

     'System.Linq.IGrouping<int,AnonymousType#1>' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'System.Linq.IGrouping<int,AnonymousType#1>' could be found (are you missing a using directive or an assembly reference?)

    Does anyone knows how to solve this?


    Tuesday, February 16, 2010 9:47 PM


  • Hi Miguel,

    The GroupBy() will return an collection of IGrouping<int, { .Id, .Name, .Centers }>.   However, it does not contain a property of Name, so the OrderBy() method will raise the compiler error that you mentioned.  If I understand your request correctly, you can refer to the following query:
    _context.Regions.Where(r => r.Centers.Count(c => c.Open == true) > 0).GroupBy(r => r.Id).
                              SelectMany(i => i, (i, r) => r).OrderBy(r => r.Name);

    Also, the OrderBy should be the last clause since other query method may break the correct order collection returned by OrderBy. 

    Does it get your expected result?  

    Best Regards,
    Lingzhi Sun
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Tuesday, February 23, 2010 1:58 PM