分享一个适用的DataTable帮助类C#版本

        在项目中常常常会使用到DataTable,尤其是后台开发人员。如果DataTable使用得当不仅能使程序简洁清晰,并且可以提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一下总结。

一、基本概念

DataTable表示一个内存内关系数据的表。个人理解:DaTable如同数据库中的表或Excel中的表,如我们常用的数据库如Mysql数据库,就是关系型数据库。

DataTable的架构由列和约束表示。 使用对象以及 ForeignKeyConstraint 和 UniqueConstraint对象定义DataTable 的架构。
DataTable中的列可以映射到数据源中的列,包含从表达式计算所得的值、自动递增它们的值,或包含主键值。
除架构以外,DataTable 还必须具有行,在其中包含数据并对数据排序。
DataRow类表示表中包含的实际数据。 DataRow 及其属性和方法用于检索、计算和处理表中的数据。在访问和更改行中的数据时,DataRow 对象会维护其当前状态和原始状态。

二、DataTableHelper帮助类主要内容

DataTable帮助类DataTableHelper,主要包括以下方法:

1、给DataTable增加一个自增列

2、检查DataTable 是否有数据行

3、DataTable转换成实体列表

4、实体列表转换成DataTable

5、将泛型集合类转换成DataTable

6、根据nameList里面的字段创建一个表格,返回该表格的DataTable

7、通过字符列表创建表字段

8、 获得从DataRowCollection转换成的DataRow数组

9、将DataRow数组转换成DataTable,注意行数组的每个元素须具有相同的数据结构

10、排序表的视图

11、根据条件过滤表的内容

三、源码分享

1、命名空间引用

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using System.Collections;

2、给DataTable增加一个自增列

/// <summary>
/// 给DataTable增加一个自增列
/// 如果DataTable 存在 identityid 字段  则 直接返回DataTable 不做任何处理
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns>返回Datatable 增加字段 identityid </returns>
public static DataTable AddIdentityColumn(DataTable dt)
{
    if (!dt.Columns.Contains("identityid"))
    {
        dt.Columns.Add("identityid");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["identityid"] = (i + 1).ToString();
        }
    }
    return dt;
}

3、检查DataTable 是否有数据行

/// <summary>
/// 检查DataTable 是否有数据行
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static bool IsHaveRows(DataTable dt)
{
    if (dt != null && dt.Rows.Count > 0)
        return true;

    return false;
}

4、DataTable转换成实体列表

/// <summary>
/// DataTable转换成实体列表
/// </summary>
/// <typeparam name="T">实体 T </typeparam>
/// <param name="table">datatable</param>
/// <returns></returns>
public static IList<T> DataTableToList<T>(DataTable table)
    where T : class
{
    if (!IsHaveRows(table))
        return new List<T>();

    IList<T> list = new List<T>();
    T model = default(T);
    foreach (DataRow dr in table.Rows)
    {
        model = Activator.CreateInstance<T>();

        foreach (DataColumn dc in dr.Table.Columns)
        {
            object drValue = dr[dc.ColumnName];
            PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);

            if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
            {
                pi.SetValue(model, drValue, null);
            }
        }

        list.Add(model);
    }
    return list;
}

5、实体列表转换成DataTable

/// <summary>
/// 实体列表转换成DataTable
/// </summary>
/// <typeparam name="T">实体</typeparam>
/// <param name="list"> 实体列表</param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(IList<T> list)
    where T : class
{
    if (list == null || list.Count <= 0)
    {
        return null;
    }
    DataTable dt = new DataTable(typeof(T).Name);
    DataColumn column;
    DataRow row;

    PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    int length = myPropertyInfo.Length;
    bool createColumn = true;

    foreach (T t in list)
    {
        if (t == null)
        {
            continue;
        }

        row = dt.NewRow();
        for (int i = 0; i < length; i++)
        {
            PropertyInfo pi = myPropertyInfo[i];
            string name = pi.Name;
            if (createColumn)
            {
                column = new DataColumn(name, pi.PropertyType);
                dt.Columns.Add(column);
            }

            row[name] = pi.GetValue(t, null);
        }

        if (createColumn)
        {
            createColumn = false;
        }

        dt.Rows.Add(row);
    }
    return dt;

}

6、将泛型集合类转换成DataTable

/// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list)
{
    return ToDataTable<T>(list, null);
}

/// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <param name="propertyName">需要返回的列的列名</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
{
    List<string> propertyNameList = new List<string>();
    if (propertyName != null)
        propertyNameList.AddRange(propertyName);

    DataTable result = new DataTable();
    if (list.Count > 0)
    {
        PropertyInfo[] propertys = list[0].GetType().GetProperties();
        foreach (PropertyInfo pi in propertys)
        {
            if (propertyNameList.Count == 0)
            {
                result.Columns.Add(pi.Name, pi.PropertyType);
            }
            else
            {
                if (propertyNameList.Contains(pi.Name))
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }
            }
        }

        for (int i = 0; i < list.Count; i++)
        {
            ArrayList tempList = new ArrayList();
            foreach (PropertyInfo pi in propertys)
            {
                if (propertyNameList.Count == 0)
                {
                    object obj = pi.GetValue(list[i], null);
                    tempList.Add(obj);
                }
                else
                {
                    if (propertyNameList.Contains(pi.Name))
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                }
            }
            object[] array = tempList.ToArray();
            result.LoadDataRow(array, true);
        }
    }
    return result;
}

7、根据nameList里面的字段创建一个表格,返回该表格的DataTable

/// <summary>
/// 根据nameList里面的字段创建一个表格,返回该表格的DataTable
/// </summary>
/// <param name="nameList">包含字段信息的列表</param>
/// <returns>DataTable</returns>
public static DataTable CreateTable(List<string> nameList)
{
    if (nameList.Count <= 0)
        return null;

    DataTable myDataTable = new DataTable();
    foreach (string columnName in nameList)
    {
        myDataTable.Columns.Add(columnName, typeof(string));
    }
    return myDataTable;
}

8、通过字符列表创建表字段

/// <summary>
/// 通过字符列表创建表字段,字段格式可以是:
/// 1) a,b,c,d,e
/// 2) a|int,b|string,c|bool,d|decimal
/// </summary>
/// <param name="nameString"></param>
/// <returns></returns>
public static DataTable CreateTable(string nameString)
{
    string[] nameArray = nameString.Split(new char[] { ',', ';' });
    List<string> nameList = new List<string>();
    DataTable dt = new DataTable();
    foreach (string item in nameArray)
    {
        if (!string.IsNullOrEmpty(item))
        {
            string[] subItems = item.Split('|');
            if (subItems.Length == 2)
            {
                dt.Columns.Add(subItems[0], ConvertType(subItems[1]));
            }
            else
            {
                dt.Columns.Add(subItems[0]);
            }
            }
    }
    return dt;
}

private static Type ConvertType(string typeName)
{
    typeName = typeName.ToLower().Replace("system.", "");
    Type newType = typeof(string);
    switch (typeName)
    {
        case "boolean":
        case "bool":
            newType = typeof(bool);
            break;
        case "int16":
        case "short":
            newType = typeof(short);
            break;
        case "int32":
        case "int":
            newType = typeof(int);
            break;
        case "long":
        case "int64":
            newType = typeof(long);
            break;
        case "uint16":
        case "ushort":
            newType = typeof(ushort);
            break;
        case "uint32":
        case "uint":
            newType = typeof(uint);
            break;
        case "uint64":
        case "ulong":
            newType = typeof(ulong);
            break;
        case "single":
        case "float":
            newType = typeof(float);
            break;

        case "string":
            newType = typeof(string);
            break;
        case "guid":
            newType = typeof(Guid);
            break;
        case "decimal":
            newType = typeof(decimal);
            break;
        case "double":
            newType = typeof(double);
            break;
        case "datetime":
            newType = typeof(DateTime);
            break;
        case "byte":
            newType = typeof(byte);
            break;
        case "char":
            newType = typeof(char);
            break;
    }
    return newType;
}

9、 获得从DataRowCollection转换成的DataRow数组

/// <summary>
/// 获得从DataRowCollection转换成的DataRow数组
/// </summary>
/// <param name="drc">DataRowCollection</param>
/// <returns></returns>
public static DataRow[] GetDataRowArray(DataRowCollection drc)
{
    int count = drc.Count;
    DataRow[] drs = new DataRow[count];
    for (int i = 0; i < count; i++)
    {
        drs[i] = drc[i];
    }
    return drs;
}

10、将DataRow数组转换成DataTable,注意行数组的每个元素须具有相同的数据结构

/// <summary>
/// 将DataRow数组转换成DataTable,注意行数组的每个元素须具有相同的数据结构,
/// 否则当有元素长度大于第一个元素时,抛出异常
/// </summary>
/// <param name="rows">行数组</param>
/// <returns></returns>
public static DataTable GetTableFromRows(DataRow[] rows)
{
    if (rows.Length <= 0)
    {
        return new DataTable();
    }
    DataTable dt = rows[0].Table.Clone();
    dt.DefaultView.Sort = rows[0].Table.DefaultView.Sort;
    for (int i = 0; i < rows.Length; i++)
    {
        dt.LoadDataRow(rows[i].ItemArray, true);
    }
    return dt;
}

11、排序表的视图

/// <summary>
/// 排序表的视图
/// </summary>
/// <param name="dt"></param>
/// <param name="sorts"></param>
/// <returns></returns>
public static DataTable SortedTable(DataTable dt, params string[] sorts)
{
    if (dt.Rows.Count > 0)
    {
        string tmp = "";
        for (int i = 0; i < sorts.Length; i++)
        {
            tmp += sorts[i] + ",";
        }
        dt.DefaultView.Sort = tmp.TrimEnd(',');
    }
    return dt;
}

12、根据条件过滤表的内容

/// <summary>
/// 根据条件过滤表的内容
/// </summary>
/// <param name="dt"></param>
/// <param name="condition"></param>
/// <returns></returns>
public static DataTable FilterDataTable(DataTable dt, string condition)
{
    if (condition.Trim() == "")
    {
        return dt;
    }
    else
    {
        DataTable newdt = new DataTable();
        newdt = dt.Clone();
        DataRow[] dr = dt.Select(condition);
        for (int i = 0; i < dr.Length; i++)
        {
            newdt.ImportRow((DataRow)dr[i]);
        }
        return newdt;
    }
}

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MarcoPro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值