0

I am trying to convert Datatable to List using C# like this

public void GetList()
{

    ds = // here my dataset;

    List<MasterList> result = new List<MasterList>();
    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
    {
        foreach (DataRow dt in ds.Tables[0].Rows)
        {
            result.Add(new MasterList()
            {
                Name = Convert.ToString(dt["Name"]),
                Address = Convert.ToString(dt["Address"]),
                City = Convert.ToString(dt["City"])
            });

        }
    }
}

this code is working fine, but I want to know easy way to convert Datatable to List and here used foreach loop.

so what's solution for this ?

H P
  • 1
  • 1
  • 6
  • 1s google http://stackoverflow.com/questions/1427484/convert-datatable-to-listt – TriV Apr 08 '17 at 05:40
  • or http://stackoverflow.com/questions/208532/how-do-you-convert-a-datatable-into-a-generic-list – TriV Apr 08 '17 at 05:41

1 Answers1

3

With Linq you can do the following:

List<MasterList> result = ds.Tables[0].AsEnumerable().Select(dtRow => new MasterList()
{
    Name = Convert.ToString(dtRow["Name"]),
    Address = Convert.ToString(dtRow["Address"]),
    City = Convert.ToString(dtRow["City"])
}).ToList()
granadaCoder
  • 26,328
  • 10
  • 113
  • 146
Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27