lundi 1 juin 2015

Generic method for retriving a single object c#

I've been looking at this method for a while now and trying to figure out how it works. This clearly works for returning a list of objects just perfect. But what I can't currently figure out is how I would retrive a single object for instance "Employee e" and not "List"?

public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
    try
    {
        List<T> list = new List<T>();

        foreach (var row in table.AsEnumerable())
        {
            T obj = new T();

            foreach (var prop in obj.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                    propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                }
                catch
                {
                    continue;
                }
            }

            list.Add(obj);
        }

        return list;
    }
    catch
    {
        return null;
    }
}





Aucun commentaire:

Enregistrer un commentaire