LINQ How to select more than 1 property in a lambda expression?
40,151
Solution 1
MyList.Select(x => new { x.Id, x.Name }).ToList();
Solution 2
The feature you're interested in is C# 3's Anonymous Types
You can create a new instance of an anonymous type with:
var v = new { Amount = 108, Message = "Hello", this.Text };
Of course this works as a lamda too:
SomeThing.Select( () => new {X=1,Y=2} )
anywhere in your code. It also picks up property names, in which case you don't need to specify it explicitly(the third member of the anonymous type in my example is automatically named Text
.
Unfortunately you can't use them as a non generic return-type of a function.
Solution 3
var sample = dbcontext.MyList
.Select(m => new Mylist{ sampleid=m.sampleid,item=m.item })
.ToList();
Comments
-
Tony over 3 years
We often use the following lambda expression
MyList.Select(x => x.Id).ToList();
Is possible to get more than 1 property usinglambda expression ? E.g
Id
andName
from MyList?I know that I can use the following syntax:
(from item in MyList select new { item.Id, item.Name }).ToList();
Can I do the same thing using lambda expression?