将DataTable转换为List <t>

时间:2018-02-19 19:55:40

标签: c#

有没有办法在不指定单个字段的情况下从DataTable转换为List<Task>?更简洁?属性推断?

public class Task
{
    public int Id { get; set; }
    public string Name { get; set; }
}


public class TasksDAL
{

    public static List<Task> GetTasks()
    {
        DataTable dt = GetTasksDT();
        List<Task> tasks = new List<Task>();
        tasks = (from DataRow row in dt.Rows
                 select new Task
                 {
                     Id = (int)row["Id"],
                     Name = row["Name"].ToString()
                 }).ToList();

        return tasks;
    }

}

2 个答案:

答案 0 :(得分:0)

我有这个旧的代码部分,它使用反射从数据表中填充obj列表。

列的名称必须与属性的名称相同。

<VirtualHost SERVER_IP:443>
    ServerName example.com 
    ServerAlias www.example.com
    DocumentRoot /path/to/site
    ErrorLog /var/log/site.error.log

    SSLEngine On
    SSLProtocol protocols
    SSLCertificateFile path/to/certs 
    SSLCertificateKeyFile path/to/certs
    SSLCACertificateFile path/to/certs

    ProxyPass /blog http://blog.example.com/blog
    ProxyPassReverse /blog http://blog.example.com/blog

    <Directory /path/to/site>
        Options FollowSymLinks
        AllowOverride All
        DirectoryIndex index.php
        Allow from all
        Require all granted
    </Directory>

</VirtualHost>

答案 1 :(得分:0)

我更愿意将IEnumerable返回到List并反映相反的方向,为所有属性和字段指定匹配的列名:

使用MemberInfo上的某些扩展来处理属性或字段:

public static object GetValue(this MemberInfo member, object srcObject) {
    if (member.MemberType == MemberTypes.Property)
        return ((PropertyInfo)member).GetValue(srcObject, null);
    else if (member.MemberType == MemberTypes.Field)
        return ((FieldInfo)member).GetValue(srcObject);
    else
        throw new Exception("Property must be of type FieldInfo or PropertyInfo");
}

public static void SetValue<T>(this MemberInfo member, object destObject, T value) {
    if (member.MemberType == MemberTypes.Property)
        ((PropertyInfo)member).SetValue(destObject, value);
    else if (member.MemberType == MemberTypes.Field)
        ((FieldInfo)member).SetValue(destObject, value);
    else
        throw new Exception("Property must be of type FieldInfo or PropertyInfo");
}

public static Type GetMemberType(this MemberInfo member) {
    switch (member.MemberType) {
        case MemberTypes.Field:
            return ((FieldInfo)member).FieldType;
        case MemberTypes.Property:
            return ((PropertyInfo)member).PropertyType;
        case MemberTypes.Event:
            return ((EventInfo)member).EventHandlerType;
        default:
            throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member");
    }
}

您可以获取包含列的成员列表并分配它们:

public static IEnumerable<T> ToEnumerable<T>(this DataTable dt) where T : new() {
    var props = typeof(T).GetMembers(BindingFlags.Public|BindingFlags.Instance)
                         .Where(p => dt.Columns.Contains(p.Name) && (p.MemberType == MemberTypes.Field || p.MemberType == MemberTypes.Property)).ToList();
    foreach (var row in dt.AsEnumerable()) {
        var aT = new T();
        foreach (var p in props)
            p.SetValue(aT, row[p.Name]);
        yield return aT;
    }
}