Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How to convert datatable into collection without using loop in MVC? Please help.
Posted
Updated 10-Jun-15 22:34pm
v2
Comments
Mehdi Gholam 11-Jun-15 3:06am    
Iteration requires a loop.
xszaboj 11-Jun-15 3:59am    
Is there any particular reason why you don't want to use loop?
RanceAmit 11-Jun-15 4:38am    
we will create a datatable, pass it into a method, the method will return a collection.
our application understands collection, not anything else
using collection we can create json or xml string easily

1 solution

C#
public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
}


C#
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));

dt.Rows.Add(1, "John");
dt.Rows.Add(2, "Dave");

List<Person> people = ((IEnumerable)dt.Rows).Cast<DataRow>().Select(r => new Person { ID = (int)r["ID"], Name = (string)r["Name"] }).ToList();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900