封装方法

DataTable 转换 List

点击查看代码1
/// <summary>
/// Datatable类型转换list   author:zc
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="datatable"></param>
/// <param name="mapData">key 映射到 value, 如 {key: name, value: 'Name'}</param>
/// <returns></returns>
public static List<T> zcDatatableToList<T>(DataTable datatable, Dictionary<string, string> mapData)
{
    var type = typeof(T);
    var dataList = new List<T>();

    // 第一个item 是表字段,第二个可选,第二个是实体的属性
    var cols = new List<Tuple<string,string>>();
    for (var i = 0; i< datatable.Columns.Count; i++)
    {
        // 查找需要映射的值
        string item1 = datatable.Columns[i].ColumnName;
        string item2 = null;
        if (mapData != null && mapData.ContainsKey(item1))
            item2 = mapData[item1];
        cols.Add(new Tuple<string, string>(item1,item2));
    }
    foreach (DataRow row in datatable.Rows)
    {
        // 如果中有一行为空,则不往下走
        if (row.ItemArray.All(i=> string.IsNullOrWhiteSpace(i.ToString()) ))
            break;

        var data = Activator.CreateInstance<T>();
        // 是否往list添加
        var flagAdd = false;
        foreach (var col in cols)
        {
            var pro = string.IsNullOrWhiteSpace(col.Item2) ? col.Item1 : col.Item2;
            var proObj = type.GetProperty(pro,BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            if (proObj == null)
                continue;
            proObj.SetValue(data, row[col.Item1]);
            flagAdd = true;
        }
        if(flagAdd)
            dataList.Add(data);
    }
    return dataList;
}
posted @ 2023-01-10 11:35  Pro成  阅读(27)  评论(0编辑  收藏  举报