如何在C#中将DataTable转换为通用列表

时间:2016-08-10 06:11:16

标签: c# asp.net

我需要将C#DataTable转换为通用收集列表

DataTable Columns Respectively

 1. EmpId  (this is Int DataType)
 2. EmpName   (this is varchar DataType)
 3. EmpAddress  (this is varchar DataType)
 4. EmpPhone  (this is varchar DataType)
 5. Status   (this is Boolean DataType)
 6. EmpRelationKey (this is int DataType)

所以我的DataTable包含上述字段的值。在这里,我需要将此值分配到我的列表中

我的列表变量分别

class Employee
{
protected int EmpId  ;
protected string EmpName =String.Empty;
protected string EmpAddress  = String.Empty;
protected string EmpPhone  = String.Empty;
protected bool Status ;
protected int EmpRelationKey ;
}

Declaring List
List<Employee> Emp= new List<Employee>

所以现在我需要将DataTable值分配给此List。代码应该非常专业。

我尝试过这种方法

List<Employee>employees = new List<Employee>();  

foreach (DataRow row in dt.Rows)  
{  
   employees.Add(new Employee  
   {  
   EmpId  = Convert.ToInt32(row["EmpId"]), 
   EmpName = row["EmpName"].ToString() ,
   EmpAddress =   row["EmpName"].ToString(),
   Emphone =   row["EmpPhone"].ToString(),
   Status = Convert.toBoolean(row["Status"])
   });  
}   

但我不想提及列名,是否还有其他方法来分配值而不提及DataTable中的每个列名

4 个答案:

答案 0 :(得分:2)

 $scope.check = true;

然后,

using System.Reflection;

使用示例:

public static List<T> BindList<T>(DataTable dt)
{
    // Example 1:
    // Get private fields + non properties
    //var fields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

    // Example 2: Your case
    // Get all public fields
    var fields = typeof(T).GetFields();

    List<T> lst = new List<T>();

    foreach (DataRow dr in dt.Rows)
    {
        // Create the object of T
        var ob = Activator.CreateInstance<T>();

        foreach (var fieldInfo in fields)
        {
            foreach (DataColumn dc in dt.Columns)
            {
                // Matching the columns with fields
                if (fieldInfo.Name == dc.ColumnName)
                {
                    // Get the value from the datatable cell
                    object value = dr[dc.ColumnName];

                    // Set the value into the object
                    fieldInfo.SetValue(ob, value);
                    break;
                }
            }
        }

        lst.Add(ob);
    }

    return lst;
}

=====================

扩展版

上面的例子假设DataTable中保存的数据与 Class对象的字段具有相同的数据类型

如果数据与您的类对象的字段不同,该怎么办?

例如 null

因此,您可能希望扩展该方法,以防两种数据类型不同。

DataTable dt1 = SqlHelper.GetTable("select * from employee;");
List<Employee> employees = BindList<Employee>(dt1);

DataTable dt2 = SqlHelper.GetTable("select * from membership;");
List<Membership> lstMembership = BindList<Membership>(dt2);

DataTable dt3 = SqlHelper.GetTable("select * from car order by name;");
List<Car> lstCar = BindList<Car>(dt3);

答案 1 :(得分:1)

您可以尝试这样的事情:

List<Employee> listObject = dTable.AsEnumerable()
                                  .Select(x => new Employee()
                                  {
                                    EmpId = x.Field<int>("EmpId"),
                                    EmpName = x.Field<string>("EmpName"),
                                    EmpAddress = x.Field<string>("EmpName"),
                                    EmpPhone = x.Field<string>("EmpPhone"),
                                    Status = x.Field<bool>("Status"),
                                    EmpRelationKey = x.Field<int>("EmpRelationKey")
                                  }).ToList();

答案 2 :(得分:0)

使用LinQ,你可以做到,

  List<DataRow> list = Datatablle.AsEnumerable().ToList();

更新了答案。创建将数据表转换为列表的Helper类

public static class Helper
{

    public static List<T> ConvertDataTableToList<T>(this DataTable table) where T : class, new()
    {
        try
        {
            List<T> list = new List<T>();

            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();

                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                        continue;
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        catch
        {
            return null;
        }
    }
}

然后,

DataTable dtDatatable = GetEmployee();
List<Employee> employeeList = dtDatatable.ConvertDataTableToList<Employee>();

答案 3 :(得分:0)

正如评论中所述,每当您对DataTable结构进行任何更改时,这些更改也必须在Class中完成,如果您更改Class,则将这些更改与{{1}同步}} 结构体。

DataTable
不要忘记List<Employee>employees = new List<Employee>(); foreach (DataRow row in dt.Rows) { Employee emp= new Employee(); PropertyInfo[] properties = typeof(Employee).GetProperties(); for (int i = 0; i < properties.Length; i++) { property.SetValue(emp, Convert.ChangeType(row[i], property.GetType())); } }

相关问题