版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
using System;
using System.Data;
using System.Reflection;
namespace System.Collections.Generic
{
public static class IEnumerableExtend
{
/// <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;
}
}
}
}
}
测试
using System;
using System.Collections.Generic;
using System.Data;
namespace Test
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
static void Main(string[] args)
{
List<Person> list = new List<Person>();
for (int i = 0; i < 5; i++)
{
list.Add(new Person { Age = i, Name = "Test" + i });
}
list.Add(new Person { Age = 3, Name = "Test" });
DataTable table1 = list.ToDataTable();
DataTable table2 = list.DistinctBy(d => d.Age).ToDataTable();
Console.Read();
}
}
}
调试
table1的结果
table2的结果