Convert List<a> to List<b> Using ConvertAll in C#

I see many developers convert one list to another list using foreach. It is okay and gets the job done but there is a more convenient way to convert one list to another list; use ConvertAll();

Just to explain the scenario better, let us assume you have the following two classes. The InternalStudent class represents the Student class internally in the project and this is not supposed to be exposed in Service and so on.

  1. public class InternalStudent  
  2. {  
  3.     public string IName { getset; }  
  4.     public int IAge { getset; }  
  5. }  
Another class is Student as in the following:
  1. public class Student  
  2. {  
  3.   public string Name { getset; }  
  4.   public int Age { getset; }  
  5. }  
Now you have a list of InternalStudents as below:
  1. List<InternalStudent> lstInterStudent = new List<InternalStudent>  
  2. {  
  3.     new InternalStudent {IName="dj",IAge=32},  
  4.     new InternalStudent{IName="pinal",IAge=36}  
  5. };  
the requirements are to convert the List<InternalStudent> to a List<Student>. Usually we convert one list to another list using foreach as given below:
  1. List<Student> lstStudent = new List<Student>();  
  2. foreach(InternalStudent s in lstInterStudent)  
  3. {  
  4.     lstStudent.Add(new Student  
  5.         {  
  6.             Name = s.IName,  
  7.             Age = s.IAge  
  8.         });  
  9. }  
There is no problem, as such, in this way of conversion from one generic list to another generic list. However there is a more convenient way to do this conversion.
  1. List<Student> lstStudent = lstInterStudent.ConvertAll(x => new Student  
  2. {  
  3.     Age = x.IAge,  
  4.     Name = x.IName  
  5. });  
We are using ConvertAll to convert one generic list to another generic list. I hope you find this article useful. Thanks for reading.

 

Up Next
    Ebook Download
    View all
    Learn
    View all