C# DataTable转换成List的方法与测试

C#开发 2014-04-02 43085阅读 0评论 0收藏 收藏本文
刚才看到博客园的一个讨论,C# DataTable 转 List(大家进来讨论讨论) ,提供一个参考http://stackoverflow.com/questions/1427484/convert-datatable-to-listt),具体实现和测试如下:
class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Start...");
      Console.WriteLine("Add data to datatable...");
      var dt = new DataTable();
      dt.Columns.Add("Id", typeof(Int32));
      dt.Columns.Add("Name", typeof(String));
      dt.Columns.Add("Email", typeof(String));
      dt.Columns.Add("Age", typeof(Int32));
      for (int i = 1; i <= 5; i++)
      {
        var dr = dt.NewRow();
        dr["Id"] = i;
        dr["Name"] = "Name " + i;
        dr["Email"] = "Eamil " + i;
        dr["Age"] = 20 + i;
        dt.Rows.Add(dr);
      }
      var list = ConvertTo<User>(dt);
      list.ForEach(x =>
      {
        Console.WriteLine("Element==>>Id:{0},Name:{1},Email:{2},Age:{3}", x.Id, x.Name, x.Email, x.Age);
      });
      Console.WriteLine("The end,press any key to exit...");
      Console.ReadKey();
    }

    public static List<T> ConvertTo<T>(DataTable dt) where T : new()
    {
      var list = new List<T>();
      try
      {
        var columnNames = new List<string>();
        foreach (DataColumn col in dt.Columns)
        {
          columnNames.Add(col.ColumnName);
        }
        PropertyInfo[] Properties;
        Properties = typeof(T).GetProperties();
        list = dt.AsEnumerable().ToList().ConvertAll<T>(x => GetObject<T>(x, columnNames, Properties));
      }
      catch { }
      return list;
    }

    public static T GetObject<T>(DataRow row, List<string> columnsName, PropertyInfo[] properties) where T : new()
    {
      T obj = new T();
      try
      {
        string columnname = "";
        string value = "";
        foreach (PropertyInfo objProperty in properties)
        {
          columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
          if (!string.IsNullOrEmpty(columnname))
          {
            value = row[columnname].ToString();
            if (!string.IsNullOrEmpty(value))
            {
              if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
              {
                value = row[columnname].ToString().Replace("$", "").Replace(",", "");
                objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
              }
              else
              {
                value = row[columnname].ToString().Replace("%", "");
                objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
              }
            }
          }
        }
        return obj;
      }
      catch
      {
        return obj;
      }
    }
  }

  public class User
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
  }
以上实现源自:http://stackoverflow.com/questions/1427484/convert-datatable-to-listt 谢谢博客园辉_辉的建议,将typeof(T).GetProperties()在GetObjct<T>()的外部来调用,这样可以避免每个DataRow都调用一次typeof(T).GetProperties()方法。 该实现还有需要优化的地方,仅供参考实现的思路。 最近更新的一篇关于DataTable转换成List<T>的文章http://2sharings.com/2014/c-sharp-linq-convert-datatable-to-list

转载请注明:图享网 » C# DataTable转换成List的方法与测试

文章评论

获取验证码