Create a list of one object type from a list of another using Linq

Jeremy picture Jeremy · Nov 9, 2009 · Viewed 27.3k times · Source

If I have classes of Type A and B:

public class A
{
    public int TotalCount;
    public string Title;
}

public class B
{
    public int Count;
    public string Title;
}

I have a list of instances A instances, what is the most efficient way to create and populate a List of type B using Linq?

Answer

Daniel M picture Daniel M · Nov 9, 2009
List<B> listB = listA.Select(a => new B()
   {
        Count = a.TotalCount,
        Title = a.Title
   }).ToList();

Does the same as eduncan's solution with different syntax. Take your pick..