zoukankan      html  css  js  c++  java
  • C#将List<T>转化为DataTable

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Reflection;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        static class ConvertDatatable
        {
            /// <summary>
            /// 扩展方法:将List<T>转化为DataTable
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="list"></param>
            /// <returns></returns>
            public static DataTable ToDataTable<T>(this List<T> list)
            {
                DataTable datatable = new DataTable();
                PropertyInfo[] propInfo = typeof(T).GetProperties(BindingFlags.Public|BindingFlags.Instance);
                foreach (var item in propInfo)
                {
                    datatable.Columns.Add(item.Name);
                }
                foreach (T item in list)
                {
                    var values=new object[propInfo.Length];
                    for (int i = 0; i < propInfo.Length; i++)
                    {
                        values[i] = propInfo[i].GetValue(item, null);
                    }
                    datatable.Rows.Add(values);
                }
                return datatable;
            }
        }
    
        class Student
        {
            public int? id { get; set; }
            public string name { get; set; }
            public int? age { get; set; }
            public string address { get; set; }
        }
    }

    调用:

        class Program
        {
            static void Main(string[] args)
            {
                List<Student> listStu = new List<Student>()
                {
                    new Student(){id=1,name="张三",age=2,address="东十路1号"},
                    new Student(){id=2,name="李四",age=8}
                };
    
                DataTable dt = listStu.ToDataTable<Student>();
    
                foreach (DataRow item in dt.Rows)
                {
                    Console.Write(item["id"].ToString());
                    Console.Write(item["name"].ToString());
                    Console.Write(item["age"].ToString());
                    Console.Write(item["address"].ToString());
                    Console.WriteLine("
    ");
                }
                Console.Read();
            }
        }
  • 相关阅读:
    Oracle SQL语句大全(一)
    数据查询(3)-复杂查询(芮)
    数据查询(2)-高级查询(芮)
    数据查询(1)-简单查询(芮)
    T-SQL(5)-操作数据行(芮)
    T-SQL(4)-功能函数(芮)
    T-SQL(3)-批处理(芮)
    T-SQL(2)-逻辑控制(芮)
    T-SQL(1)-变量(芮)
    如何设计数据库(2)?(芮)
  • 原文地址:https://www.cnblogs.com/AlexOneBlogs/p/8044494.html
Copyright © 2011-2022 走看看