score:2

Accepted answer

Take a look at tis fragment:

group N by N.STG_nt into G

The part between by and into is the key(s), and similar to SQL there you have access to all aliases (variables) from from and join clauses. The name after into is LINQ specific and represents the alias (variable) for accessing the GroupBy result. But what is between group and 'by'? There is no SQL equivalent.

Well, the result of GroupBy is of type IGrouping<TKey, TElement>, which has property TKey Key and also is IEnumerable<TElement>. The TKey is comong from the expression between by and into, while TElement (which is what you can access through into variable is coming from the expression between group and by.

In your sample you've put N there, that`s why you have access only to its properties.

In order to have access to other properties, you would use the typical LINQ construct for "composite" things, which is anonymous type projection, e.g.

var R = (
    from N in SCHOOL_DB_Context.Con.NT_CTR
    join S in SCHOOL_DB_Context.Con.STGs on N.STG_nt equals S.CD_STG
    where N.CTR_nt == CTR
    group new { N, S } by N.STG_nt into G
    select new NT_CTR_Anal
    {
        G.Key, // N.STG_nt
        SomeNPropSum = G.Sum(e => e.N.SomeNProp),
        SomeSPropSum = G.Sum(e => e.S.SomeSProp),
    };

As you can see, now you have access to both N and S properties inside grouping aggregate methods.


Related Articles