Rohit
Rohit

Reputation: 10236

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.

Upvotes: 10

Views: 16775

Answers (3)

user1968030
user1968030

Reputation:

You can use this

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

Upvotes: 2

Matt
Matt

Reputation: 6953

Try this:

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

Upvotes: 2

JaredPar
JaredPar

Reputation: 754745

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

Upvotes: 18

Related Questions