简体   繁体   English

是否可以在C#中的LINQ扩展方法中创建匿名类型?

[英]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#? 是否可以在C#中的LINQ扩展方法中创建匿名类型?

For example LINQ query.ie 例如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#? C#中的LINQ扩展方法是否支持相同的行为?

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. C#语言规范在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. 请注意,在这种情况下,由于您的join子句后跟一个select子句,因此投影是在Join调用内执行的。 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. 否则(例如,如果您有where子句),编译器将引入透明标识符,以通过一个新的匿名类型(使它们对保持在单个值中)来保持两个范围变量( tempcasect )可用。

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. 您显示的LINQ查询一种扩展方法。 It will simply be transformed by the compiler into a call to the Join extension method. 编译器会将其简单地转换为对Join扩展方法的调用。 You can create an anonymous type anywhere you can create any type, which include inside any extension methods. 您可以在任何可以创建任何类型的位置(包括任何扩展方法内部)创建匿名类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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