"A lambda expression with a statement body cannot be converted to an expression tree"
Is objects
a Linq-To-SQL database context? In which case, you can only use simple expressions to the right of the => operator. The reason is, these expressions are not executed, but are converted to SQL to be executed against the database.
Try this
Arr[] myArray = objects.Select(o => new Obj() {
Var1 = o.someVar,
Var2 = o.var2
}).ToArray();
You can use statement body in lamba expression for IEnumerable collections. try this one:
Obj[] myArray = objects.AsEnumerable().Select(o =>
{
var someLocalVar = o.someVar;
return new Obj()
{
Var1 = someLocalVar,
Var2 = o.var2
};
}).ToArray();
Notice:
Think carefully when using this method, because this way, you will have all query result in memory, that may have unwanted side effects on the rest of your code.
It means that you can't use lambda expressions with a "statement body" (i.e. lambda expressions which use curly braces) in places where the lambda expression needs to be converted to an expression tree (which is for example the case when using linq2sql).
Without knowing more about what you are doing (Linq2Objects, Linq2Entities, Linq2Sql?), this should make it work:
Arr[] myArray = objects.AsEnumerable().Select(o => {
var someLocalVar = o.someVar;
return new Obj() {
Var1 = someLocalVar,
Var2 = o.var2
};
}).ToArray();