C# List and DataTable 互转

using System;
using System.Data;
using System.Reflection;

namespace LEInbound.Application.Helper;
public static class DataTableToList
{
    /// <summary>
    /// DataTable转换成IEnumerable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataTable"></param>
    /// <returns></returns>
    public static IEnumerable<T> ToEnumerable<T>(this DataTable dataTable) where T : class, new()
    {
        return dataTable.AsEnumerable().Select(s => s.ToModel<T>());
    }

    /// <summary>
    /// DataRow转换成Model
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataRow"></param>
    /// <returns></returns>
    public static T ToModel<T>(this DataRow dataRow) where T : class, new()
    {
        T model = new T();
        foreach (var property in model.GetType().GetProperties())
        {
            foreach (DataColumn key in dataRow.Table.Columns)
            {
                string columnName = key.ColumnName;
                if (!string.IsNullOrEmpty(dataRow[columnName].ToString()))
                {
                    string propertyNameToMatch = columnName;
                    if (property.Name.ToLower() == propertyNameToMatch.ToLower())
                    {
                        Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                        object safeValue = (dataRow[columnName] == null) ? null : Convert.ChangeType(dataRow[columnName], t);
                        property.SetValue(model, safeValue, null);
                    }
                }
            }
        }
        return model;
    }

    /// <summary>
    /// IEnumerable转换成DataTable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="varlist"></param>
    /// <returns></returns>
    public static DataTable ToDataTable<T>(this IEnumerable<T> varlist) where T : class, new()
    {
        //定义要返回的DataTable对象
        DataTable dtReturn = new DataTable();
        //安全性检查
        if (varlist == null)
        {
            return dtReturn;
        }
        //保存列集合的属性信息数组
        PropertyInfo[] oProps = typeof(T).GetProperties();
        //循环PropertyInfo数组
        foreach (PropertyInfo pi in oProps)
        {
            //得到属性的类型
            Type colType = pi.PropertyType;
            //如果属性为泛型类型
            if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
            {
                //获取泛型类型的参数
                colType = colType.GetGenericArguments()[0];
            }
            //将类型的属性名称与属性类型作为DataTable的列数据
            dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
        }
        //循环遍历集合,使用反射获取类型的属性信息
        foreach (T rec in varlist)
        {
            //新建一个用于添加到DataTable中的DataRow对象
            DataRow dr = dtReturn.NewRow();
            //循环遍历属性集合
            foreach (PropertyInfo pi in oProps)
            {
                //为DataRow中的指定列赋值
                dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
            }
            //将具有结果值的DataRow添加到DataTable集合中
            dtReturn.Rows.Add(dr);
        }
        //返回DataTable对象
        return dtReturn;
    }

    /// <summary>
    /// 去除重复数据
    /// </summary>
    /// <typeparam name="TSource"></typeparam>
    /// <typeparam name="TKey"></typeparam>
    /// <param name="source"></param>
    /// <param name="keySelector"></param>
    /// <returns></returns>
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> seenKeys = new HashSet<TKey>();
        foreach (TSource element in source)
        {
            if (seenKeys.Add(keySelector(element)))
            {
                yield return element;
            }
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值