简体   繁体   English

使用Linq连续选择多个元素

[英]Select Multiple elements in a row using Linq

My Code is as follows 我的守则如下

var users = MyTable.AsEnumerable()
                      .Select(x => new { x.Field<string>("Col1"),x.Field<string>  
                       ("Col2")}).ToList();

On compiling I get 在编译我得到

Invalid anonymous type member declarator. 无效的匿名类型成员声明符。 Anonymous type members must be declared with a member assignment, simple name or member access. 必须使用成员分配,简单名称或成员访问声明匿名类型成员。

You need to give a name to each of the fields in the anonymous type 您需要为匿名类型中的每个字段指定一个名称

var users = MyTable.AsEnumerable()
  .Select(x => 
     new { Col1 = x.Field<string>("Col1"), Col2 = x.Field<string>("Col2")})
  .ToList();

The only time the name of an anonymous type field can be omitted is when the expression itself is a simple name that the compiler can use. 唯一一次可以省略匿名类型字段的名称是表达式本身是编译器可以使用的简单名称。 For example if the expression is a field or property then the name can be omitted. 例如,如果表达式是字段或属性,则可以省略名称。 In this case the expression is a generic method call and has no name the compiler will use 在这种情况下,表达式是泛型方法调用,没有编译器将使用的名称

Try this: 试试这个:

var users = MyTable.AsEnumerable()
                      .Select(x => new
                      {
                        Col1 = x.Field<string>("Col1"),
                        Col2 = x.Field<string>("Col2")})
                        .ToList();

You can use this 你可以用它

var users = MyTable.AsEnumerable()
                      .Select(x => new
                      {
                        Col1 = x.Field<string>("Col1"),
                        Col2 = x.Field<string>("Col2")})
                        .ToList();

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

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