/// <summary>
/// http://www.codeproject.com/Tips/784090/Conversion-Between-DataTable-and-List-in-Csharp
/// </summary>
public static class ExtensionUtility
{ /// <summary>
/// Converts List To DataTable
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static DataTable ToDataTable<TSource>(this IList<TSource> data)
{
DataTable dataTable = new DataTable(typeof(TSource).Name);
PropertyInfo[] props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
} foreach (TSource item in data)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
} /// <summary>
/// Converts DataTable To List
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="dataTable"></param>
/// <returns></returns>
public static List<TSource> ToList<TSource>(this DataTable dataTable) where TSource : new()
{
var dataList = new List<TSource>(); const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
var objFieldNames = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags)
select new { Name = aProp.Name, Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType }).ToList();
var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns
select new { Name = aHeader.ColumnName, Type = aHeader.DataType }).ToList();
var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList(); foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
{
var aTSource = new TSource();
foreach (var aField in commonFields)
{
PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name);
var value = (dataRow[aField.Name] == DBNull.Value) ? null : dataRow[aField.Name]; //if database field is nullable
propertyInfos.SetValue(aTSource, value, null);
}
dataList.Add(aTSource);
}
return dataList;
}
}

  测试数据源:

public class Student
{
public long Id { get; set; }
public string Name { get; set; }
public short Age { get; set; }
public DateTime DateOfCreation { get; set; }
public bool? IsActive { get; set; }
} public class Teacher
{
public long Id { get; set; }
public string Name { get; set; }
public Nullable<int> DepartmentId { get; set; }
} public class Data
{
public static List<Student> GetStudents()
{
var list = new List<Student>
{
new Student {Id = 1, Name = "Smith", Age = 18, DateOfCreation = DateTime.Now, IsActive = true},
new Student {Id = 2, Name = "Hook", Age = 16, DateOfCreation = DateTime.Now.AddDays(-1), IsActive = true},
new Student {Id = 3, Name = "Jhon", Age = 15, DateOfCreation = DateTime.Now.AddDays(-2), IsActive = true},
new Student {Id = 4, Name = "Alan", Age = 21, DateOfCreation = DateTime.Now.AddDays(-3), IsActive = true}
};
return list;
} public static List<Teacher> GetTeachers()
{
var list = new List<Teacher>
{
new Teacher {Id = 1, Name = "Smith", DepartmentId = 18 },
new Teacher {Id = 2, Name = "Hook", DepartmentId = 16 },
new Teacher {Id = 3, Name = "Jhon", DepartmentId = 15 },
new Teacher {Id = 4, Name = "Alan", DepartmentId = 21 }
};
return list;
} public static DataTable DbNullInt()
{
DataTable table = new DataTable();
table.Columns.Add("Id", typeof(long));
table.Columns.Add("Name", typeof(string)); DataColumn column;
column = new DataColumn("DepartmentId", System.Type.GetType("System.Int32"));
column.AllowDBNull = true;
table.Columns.Add(column); table.Rows.Add(1, "Smith", DBNull.Value);
table.Rows.Add(2, "Hook", 1); return table;
}
}

  测试:

            List<Student> students = Data.GetStudents();
/*List to DataTable conversion*/
DataTable studentTbl = students.ToDataTable();
/*DataTable to List conversion*/
List<Student> newStudents = studentTbl.ToList<Student>();//ExtensionUtility.ToList<Student>(newStudents);
this.dataGridView1.DataSource = newStudents; /*List to DataTable conversion*/
DataTable teacherTbl = Data.DbNullInt();
/*DataTable to List conversion*/
List<Teacher> newTeachers = teacherTbl.ToList<Teacher>(); this.dataGridView2.DataSource = newTeachers;

  

csharp:Conversion Between DataTable and List的更多相关文章

  1. Conversion Between DataTable and List in C#

    1.List to DataTable public static DataTable ToDataTable<TSource>(this IList<TSource> dat ...

  2. Dapper 的输出参数使用示范

    -- 普通SQL 示范-- Queries with output parameters. Hide Shrink Copy Code // output parameters // the para ...

  3. csharp: Export DataTable to Excel using OpenXml 2.5 in asp.net

    //https://www.microsoft.com/en-us/download/details.aspx?id=5124 Open XML SDK 2.0 for Microsoft Offic ...

  4. csharp: DataTable Rename ColumnName and remove Column

    enum ChangeNume { /// <summary> /// 简体 /// </summary> gbk=1, /// <summary> /// 英文 ...

  5. csharp: sum columns or rows in a dataTable

    DataTable dt = setData(); // Sum rows. //foreach (DataRow row in dt.Rows) //{ // int rowTotal = 0; / ...

  6. CSharp 案例:用 Dynamic 来解决 DataTable 数值累加问题

    需求说明 给定一个 DataTable,如果从中取出数值类型列的值并对其累加? 限制:不知该列是何种数值类型. 解决方案 1.将表转换为 IEnumerable<dynamic>,而后获取 ...

  7. csharp: datatable get Column datatype or Column Name

    /// <summary> ///列表名 /// </summary> /// <param name="table"></param&g ...

  8. csharp: DataTable export to excel,word,csv etc

    http://code.msdn.microsoft.com/office/Export-GridView-to-07c9f836 https://exporter.codeplex.com/ htt ...

  9. csharp: DataTable结构相同的比较

    )
 ) * pageSize;
 ; i++)
 {
 DataRow newdr = newdt.NewRow();
 DataRow dr = dt.Rows[i];
 foreach (Dat ...

随机推荐

  1. Linux修改profile文件改错了,恢复的方法

    Linux修改profile文件改错了,恢复的方法在改profile的时候,改出问题了,除了cd以外的命令基本都不能用了,连vi都不能用了,上网查了下,用export PATH=/usr/bin:/u ...

  2. CODEVS-1215迷宫

    迷宫 原题:传送门 题目描述 Description 在N*N的迷宫内,“#”为墙,“.”为路,“s”为起点,“e”为终点,一共4个方向可以走.从左上角((0,0)“s”)位置处走到右下角((n-1, ...

  3. VS 代码自动对齐快捷键

    全部代码代码自动对齐快捷键为 Ctrl + a(按后可松松手) + k(按后可松松手) + f

  4. xshell本地上传文件至服务器

    今天本地写了个项目,想传到服务器部署起来.就上网百度了一下挺多的,一个个记录下,如有雷同,纯属抄袭. lrzsz方法 rz # 检查是否安装 yum -y install lrzsz # 安装 rpm ...

  5. mono for android读书笔记之真机调试(转)

    调试环境: 1.软件:monodevelop v3.0.3.5 2.硬件:华为C8650s手机一部,数据线一根,thinkpad e420笔记本电脑一台 调试的应用程序有一个Activity,Acti ...

  6. ACM练习网站

    1.http://www.acmerblog.com/ Acm之家 2.http://acm.nyist.net/JudgeOnline/problemset.php 南阳理工学院

  7. Idea查看代码相关技巧

    (1)查看类中的属性与方法快捷键  Alt+7 (2)查看方法被调用 在方法上右键find usages (3)查看方法说明  Ctrl+Q

  8. PHP之string之addcslashes()函数使用

    addcslashes (PHP 4, PHP 5, PHP 7) addcslashes - Quote string with slashes in a C style addcslashes - ...

  9. <数据挖掘导论>读书笔记10聚类分析续

    基于原型的聚类 模糊c均值使用模糊逻辑和模糊集合论的概念,提出一种聚类方案,它很像K均值,但是不需要硬性地将对象分派到一个簇中.模糊c均值算法有时也称为FCM 混合模型聚类采取这样的访谈,簇集合可以用 ...

  10. ASP.NET MVC Core Starter Kit

    上一篇博文<创建.NET Core程序的Nuget Package>提到准备创建一个Nuget包,用于自动生成一个简单的ASP.NET MVC Core的示例项目.本来是打算用Nuget实 ...