iJade iJade -4 years ago 214
C# Question

Convert DataSet to List

Here is my c# code

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"]) });
}


It uses a loop to create a List from a dataset.Is there any direct method or shorter method or one line code to convert dataset to list

Answer Source

Try something like this:

var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Employee{Name = dataRow.Field<string>("Name")}).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download