Saleem
Saleem

Reputation: 730

Convert DataAccess list to ObjectModel list in C#

I'm working on a multi-layered architecture project using C#. One of the methods I have to do in each class would be to convert a list of DAL objects to list of OM objects, like in the following example:

private List<OM.Employee> DAL_To_OM(List<DAL.Employee> list)
{
    List<OM.Employee> retList = list.ConvertAll(e => new OM.Employee
    {
        Name = e.Name,
        Age = e.Age
    });

    return retList;
}

My question here, is there any way to write a generic function that achieves this in a generic way, like converting List to List where both T1 and T2 have same properties?

Upvotes: 0

Views: 57

Answers (1)

bernd_rausch
bernd_rausch

Reputation: 335

You can use reflection for this (but keep in mind that reflection is slow, depending on your classes and size of lists it may be too slow):

public class Converter<T1,T2>
{
    public static List<T1> Convert(List<T2> t2List)
    {
        List<T1> t1List = t2List.ConvertAll<T1>(Convert);
        return t1List;
    }

    public static T1 Convert(T2 t2)
    {
        T1 t1 = Activator.CreateInstance<T1>();

        List<PropertyInfo> t1PropertyInfos = new List<PropertyInfo>(typeof(T1).GetProperties());
        List<PropertyInfo>  t2PropertyInfos = new List<PropertyInfo>(typeof(T2).GetProperties());
        foreach (PropertyInfo pi in t1PropertyInfos)
        {
           PropertyInfo data = t2PropertyInfos.Find(p => p.Name.Equals(pi.Name));
           if (data != null)
           {
              pi.SetValue(t1, data.GetValue(t2, new object[0]), new object[0]);
           }
       }

       return t1;
   }

}

Upvotes: 1

Related Questions