Search code examples
c#linq

LINQ with group new and by new


I am new to linq and I don't understand the part of the following program 'group new { b, c} by new { a }', can someone tell me?

Where can I refer to this,especially 'by new { a }'.

   from a in aTemp
   join b in bTemp on a.No equals b.No into bTB
   from b in bTB.DefaultIfEmpty()
   join c in cTemp on new { pa1 = b?.No ?? "", pa2 = b?.FNo ?? "" } 
               equals new { pa1 = c.No, pa2 = c.FNo } into cTB
   from c in cTB().DefaultIfEmpty()
   group new { b, c} by new { a } into z
   select new Log.Set

Solution

  • I think it should be the equivalent SQL query for you and with this, you can easily visualize it.

    SELECT a.*, b.*, c.*
    FROM aTemp a
    LEFT JOIN bTemp b ON a.No = b.No
    LEFT JOIN cTemp c ON (b.No = c.No OR b.No IS NULL) AND (b.FNo = c.FNo OR b.FNo IS NULL)
    GROUP BY a.*
    

    group new { b, c } creates a group by combining the values of b and c into a new object. It means that we want to group elements together based on their b and c values.

    by new { a } specifies that we want to group the elements based on the value of a. It creates another object with a single property a that represents the variable a from the outer query.

    into z assigns a name (z in this case) to the resulting groups of data. It's like giving a label to the groups so that we can refer to them later.

    So, overall, this part of the LINQ query groups the elements based on the values of a. Within each group, we have the corresponding values of b and c associated with that specific a value. The label z is used to refer to these groups in further processing.

    In simpler terms, think of it as putting similar elements together based on the values of a. Each group contains the related values of b and c for that particular a value.