Convert Datatable to generic list collection in c#
Class Example
Introduction :In this article i will show you how to convert Datatable to generic list collection in c# . It is very easy to conversion form DataTable to generic list collection .I have showed here as step by step
Class Example
public class City
{
public int CityId { get; set; }
public string Cityname { get; set; }
}
C# Code Convert DataTable to generic list collection :
List<City> CityCollection = new List<City>();
DataSet Ds = GetDataSet("Select CountryID,CountryName from Countrytable");
CityCollection = Ds.Tables[0].AsEnumerable().Select(data => new City() { CityId = (int)data["CountryID"], Cityname = (string)data["CountryName"] }).ToList();
public static DataSet GetDataSet(string Query)
{
DataSet Ds = new DataSet();
try
{
string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
SqlConnection Con = new SqlConnection(strCon);
SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
Da.Fill(Ds);
}
catch (Exception) { }
return Ds;
}