将DataSet转换为List

iJa*_*ade 52 c# ado.net list dataset

这是我的c#代码

Employee objEmp = new Employee();
List<Employee> empList = new List<Employee>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
    empList.Add(new Employee { Name = Convert.ToString(dr["Name"]), Age = Convert.ToInt32(dr["Age"]) });
}
Run Code Online (Sandbox Code Playgroud)

它使用循环从数据集创建List.是否有任何直接方法或更短的方法或一行代码将数据集转换为列表

Car*_*rra 84

尝试这样的事情:

var empList = ds.Tables[0].AsEnumerable()
    .Select(dataRow => new Employee
    {
        Name = dataRow.Field<string>("Name")
    }).ToList();
Run Code Online (Sandbox Code Playgroud)

  • 这就是我尝试过的--- var empList = ds.Tables [0] .AsEnumerable()。Select(dataRow =&gt; new Employee {Name = dataRow.Field &lt;string&gt;(“ Name”),Age = dataRow.Field &lt; int&gt;(“ Age”)})。ToList(); 说“指定的演员表无效” (2认同)

Nit*_*ant 30

这是将DataTable转换为对象列表的扩展方法:

    public static class Extensions
    {
        public static List<T> ToList<T>(this DataTable table) where T : new()
        {
            IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            List<T> result = new List<T>();

            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, properties);
                result.Add(item);
            }

            return result;
        }

        private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
        {
            T item = new T();
            foreach (var property in properties)
            {
                if (property.PropertyType == typeof(System.DayOfWeek))
                {
                    DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                    property.SetValue(item,day,null);
                }
                else
                {
                    if(row[property.Name] == DBNull.Value)
                        property.SetValue(item, null, null);
                    else 
                        property.SetValue(item, row[property.Name], null); 
                }
            }
            return item;
        }
    }
Run Code Online (Sandbox Code Playgroud)

用法:

List<Employee> lst = ds.Tables[0].ToList<Employee>();
Run Code Online (Sandbox Code Playgroud)

@ itay.b CODE解释:我们首先使用反射读取类T中的所有属性名称,
然后遍历datatable中的所有行并创建T的新对象,
然后使用反射设置新创建的对象的属性.

从行的匹配列单元格中选取属性值.

PS:类属性名称和表列名称必须相同


Fab*_*ler 16

var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
    Name = r.Field<string>("Name"),
    Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable
Run Code Online (Sandbox Code Playgroud)