How to linq join with groups?

Total Post:40

C#  Join 
 1439  View(s)
Rate this:

Hej, i've got a problem with linq expression. I Would like to perform join with groups of some set. This is basicly what I need:

var f = new IEnumerable<SomeClass> { ... };
var rows = new IEnumerable<SomeOtherClass> { ... };
var makedGroups = rows.GroupBy(row => row.SomeId);
var groupsJoined = (from row in makedGroups
    join allocQuant in f on row.Key.Value equals allocQuant.SomeId into gj
    select gr => new { Count = gr.Count(), Group = gj });

error is: Error 202 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.

How to write this expression properly?

  1. Post:30

    Re: How to linq join with groups?

    No longer have access to the range variables used in the initial from. That is, we can no longer talk about p or bp, you can only talk about pg.

    Now, pg is a group and so contains more than one product. All the products in a given pg group have the same SomeId (since that's what you grouped by), but I don't know if that means they all have the same BaseProductId.

    To get a base product name, you have to pick a particular product in the pg group (As you are doing with SomeId and CountryCode), and then join to BaseProducts.

    var result = from p in Products                         
     group p by p.SomeId into pg                         
     // join *after* group
     join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id         
     select new ProductPriceMinMax { 
           SomeId = pg.FirstOrDefault().SomeId, 
           CountryCode = pg.FirstOrDefault().CountryCode, 
           MinPrice = pg.Min(m => m.Price), 
           MaxPrice = pg.Max(m => m.Price),
           BaseProductName = bp.Name  // now there is a 'bp' in scope

      Modified On Apr-06-2018 04:06:20 AM