Reputation: 215
I have a list of customer as show below
List<Customer> customers = new List<Customer>()
{
new Customer{Id=1,Name="Abc",Address="USA",Mobile="78978797989" },
new Customer{Id=2,Name="XYZ",Address="UK",Mobile="985654454545" },
new Customer{Id=3,Name="Kafus",Address="London",Mobile="06548754555" }
};
I want to create a list with only ID and Name from above list means I want only 2 property in my new list object.
I am trying to do some code like this but I didn't get using lambda expression
var lists = customers.Select(s=>s.Id,s=>s.Name).ToList();
But I am getting error Can anybody help me with lambda expression to get lists with two property i.e Id and Name
Upvotes: 2
Views: 1914
Reputation: 9028
Use Tuple if you love Lambda:
var list = customers.Select(x => new Tuple<int, string>(x.Id, x.Name)).ToList();
or
var list = customers.Select(x => new { x.Id, x.Name }).ToList();
Upvotes: 1
Reputation: 3026
As @Sweeper said
You should use the Anonymous Types syntax
and this another way to do that:
var list = (from customer in customers select new { customer.Id, customer.Name }).ToList();
Upvotes: 1