Home > DeveloperSection > Forums > How to linq join with groups?
Anurag Sharma
Anurag Sharma

Total Post:40

Posted on    November-04-2014 2:43 AM

 LINQ C#  Join 

 1 Reply(s)
 666  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?

David Miller

Total Post:30

Posted on    November-04-2014 5:32 AM

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-05-2016 04:04:22 AM

Don't want to miss updates? Please click the below button!

Follow MindStick