I want to select some fields from a datarow doing something like:
var result = datatable.AsEnumerable()
.Select(x => new { x.Field<string>("Field1"), x.Field<string>("Field2")});
Unfortunately this isn’t working saying:
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
How can I achieve what I want?
Edit: As it seems there are (at least) two ways to achieve it:
-
Name ’em:
var result = datatable.AsEnumerable().Select(x => new { Field1 = x.Field("Field1"), Field2 = x.Field("Field2") }); -
Create a new object
Let’s say we have a class
class MyClass
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public MyClass(string field1, string field2)
{
this.Field1 = field1;
this.Field2 = field2;
}
}
we can do the following:
var result = datatable.AsEnumerable()
.Select(x => new MyClass(x.Field<string>("Field1"), x.Field<string>("Field2")));
You need to give the members of your anonymous type some names.
If you think about it, no names would make it very difficult to refer to the properties later, you’d have to use reflection and some guess work. In any case, the names need to be defined so that the anonymous type can be created for you, behind the scenes.
If you prefer returning a
Tupleinstead of an anonymous type you can doThen you can access the members with
Item1andItem2respectively.However, the
Tupleclass is new to .Net 4.0 and your question is tagged 3.5In response to your comment, you could always declare your own type
Which, obviously you would use like this,