2

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

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.