2

I have two objects that are very similar in structure, let's call them A and B. A and B share similar properties, such as first name, last name and Dob.

I have an IEnumerable<A>, which is filled with a number of A objects. I'd like to be able to iterate through each object found in A, use its details to instantiate a new object of B, and then add to a new List<B>.

I can do this longhand, but I'm positive there's a way to do this using Linq as I've seen something similar in the past, but I can't remember exactly how to do it.

The long hand would be:

List<B> list = new List<B>();

foreach (A a in AEnumerable)
{
    B b = new B
    {
        FirstName = a.Forename,
        LastName = a.Surname,
        Dob = a.DateOfBirth
    };

    list.Add(b);
}

But I'm unsure how this could be done using Linq.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194

1 Answers1

4

use Select then ToList:

var result = AEnumerable.Select(e => new B
                {
                    FirstName = e.Forename,
                    LastName = e.Surname,
                    Dob = e.DateOfBirth
                }).ToList();
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126