zoukankan      html  css  js  c++  java
  • DataSet转换为实体类

    /// <summary>
    /// DataSet转换为实体类
    /// </summary>
    /// <typeparam name="T">实体类</typeparam>
    /// <param name="p_DataSet">DataSet</param>
    /// <param name="p_TableIndex">待转换数据表索引</param>
    /// <returns>实体类</returns>
    public static T DataSetToEntity<T>(DataSet p_DataSet, int p_TableIndex)
    {
        if (p_DataSet == null || p_DataSet.Tables.Count < 0)
     return default(T);
        if (p_TableIndex > p_DataSet.Tables.Count - 1)
     return default(T);
        if (p_TableIndex < 0)
     p_TableIndex = 0;
        if (p_DataSet.Tables[p_TableIndex].Rows.Count <= 0)
     return default(T);
    
        DataRow p_Data = p_DataSet.Tables[p_TableIndex].Rows[0];
        // 返回值初始化
        T _t = (T)Activator.CreateInstance(typeof(T));
        PropertyInfo[] propertys = _t.GetType().GetProperties();
        foreach (PropertyInfo pi in propertys)
        {
     if (p_DataSet.Tables[p_TableIndex].Columns.IndexOf(pi.Name.ToUpper()) != -1 && p_Data[pi.Name.ToUpper()] != DBNull.Value)
     {
         pi.SetValue(_t, p_Data[pi.Name.ToUpper()], null);
     }
     else
     {
         pi.SetValue(_t, null, null);
     }
        }
        return _t;
    }
    
    /// <summary>
    /// DataSet转换为实体列表
    /// </summary>
    /// <typeparam name="T">实体类</typeparam>
    /// <param name="p_DataSet">DataSet</param>
    /// <param name="p_TableIndex">待转换数据表索引</param>
    /// <returns>实体类列表</returns>
    public static IList<T> DataSetToEntityList<T>(DataSet p_DataSet, int p_TableIndex)
    {
        if (p_DataSet == null || p_DataSet.Tables.Count < 0)
     return default(IList<T>);
        if (p_TableIndex > p_DataSet.Tables.Count - 1)
     return default(IList<T>);
        if (p_TableIndex < 0)
     p_TableIndex = 0;
        if (p_DataSet.Tables[p_TableIndex].Rows.Count <= 0)
     return default(IList<T>);
    
        DataTable p_Data = p_DataSet.Tables[p_TableIndex];
        // 返回值初始化
        IList<T> result = new List<T>();
        for (int j = 0; j < p_Data.Rows.Count; j++)
        {
     T _t = (T)Activator.CreateInstance(typeof(T));
     PropertyInfo[] propertys = _t.GetType().GetProperties();
     foreach (PropertyInfo pi in propertys)
     {
         if (p_Data.Columns.IndexOf(pi.Name.ToUpper()) != -1 && p_Data.Rows[j][pi.Name.ToUpper()] != DBNull.Value)
         {
      pi.SetValue(_t, p_Data.Rows[j][pi.Name.ToUpper()], null);
         }
         else
         {
      pi.SetValue(_t, null, null);
         }
     }
     result.Add(_t);
        }
        return result;
    }
    
  • 相关阅读:
    索引与搜索框架Lucene
    AutoResetEvent和ManualResetEvent的理解
    hadoop mapreduce 过程详解
    使用Visual Studio进行代码度量
    MethodImplAttribute 类和 SynchronizationAttribute 类
    开发定时服务应用
    DispatcherTimer与Dispatcher小小应用
    WCF问题
    玩转博客园的心路总结
    工作中碰到的一些东西【弹出窗口】【拖放】【异步文件上传】
  • 原文地址:https://www.cnblogs.com/Kconnie/p/5162014.html
Copyright © 2011-2022 走看看