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.
- public class InternalStudent
- {
- public string IName { get; set; }
- public int IAge { get; set; }
- }
Another class is Student as in the following:
- public class Student
- {
- public string Name { get; set; }
- public int Age { get; set; }
- }
Now you have a list of InternalStudents as below:
- List<InternalStudent> lstInterStudent = new List<InternalStudent>
- {
- new InternalStudent {IName="dj",IAge=32},
- new InternalStudent{IName="pinal",IAge=36}
- };
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:
- List<Student> lstStudent = new List<Student>();
- foreach(InternalStudent s in lstInterStudent)
- {
- lstStudent.Add(new Student
- {
- Name = s.IName,
- Age = s.IAge
- });
- }
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.
- List<Student> lstStudent = lstInterStudent.ConvertAll(x => new Student
- {
- Age = x.IAge,
- Name = x.IName
- });
We are using ConvertAll to convert one generic list to another generic list. I hope you find this article useful. Thanks for reading.