简体   繁体   中英

Is it possible to create anonymous type in LINQ extension methods in C#?

Is it possible to create anonymous type in LINQ extension methods in C#?

For example LINQ query.ie

var CAquery = from temp in CAtemp
 join casect in CAdb.sectors
 on temp.sector_code equals casect.sector_code
 select new
 {       
     //anonymous types
     CUSIP = temp.equity_cusip,
     CompName = temp.company_name,
     Exchange = temp.primary_exchange       
 };

Is the same behavior supported for LINQ extension methods in C#?

Do you mean "when using the extension method syntax"? If so, absolutely. Your query is exactly equivalent to:

var CAquery = CAtemp.Join(CAdb.sectors,
                          temp => temp.sector_code,
                          casect => casect.sector_code,
                          (temp, casect) => new
                          {       
                              CUSIP = temp.equity_cusip,
                              CompName = temp.company_name,
                              Exchange = temp.primary_exchange       
                          });

The C# language specification sets out all the translations in section 7.16. Note that in this case, as your join clause was only followed by a select clause, the projection is performed within the Join call. Otherwise (eg if you had a where clause) the compiler would have introduced transparent identifiers to keep the two range variables ( temp and casect ) available, via a new anonymous type which just kept the pair of them in a single value.

Every query expression is expressible as non-query-expression code. Query expressions are effectively a form of preprocessing.

something like this maybe...

var CAquery=CATemp.Join(.....)
                  .Select(temp=>new
                           {       
                           CUSIP = temp.equity_cusip,
                           CompName = temp.company_name,
                           Exchange = temp.primary_exchange       
                           });

The LINQ query you have shown is an extension method. It will simply be transformed by the compiler into a call to the Join extension method. You can create an anonymous type anywhere you can create any type, which include inside any extension methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM