Pages

Friday, February 17, 2012

Convert Datatable to generic list collection in c#

Convert Datatable to generic list collection in c#

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;
}


Related Other posts

9 comments:

  1. Dear AsEnumerable is NOT available in datatable class methods.

    Please suggest.
    Jay

    ReplyDelete
  2. hi, this code works fine
    if u extend the columns more than 13..i am facing an error wat to do....plz help me

    ReplyDelete
  3. Thanks for such a great article here. I was searching for something like this for quite a long time and at last, I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays. Well written article Thank You for Sharing with Us pmp training centers in chennai| pmp training in velachery | project management courses in chennai |pmp training in chennai | pmp training institute in chennai

    ReplyDelete
  4. Hey, Wow all the posts are very informative for the people who visit this site. Good work! We also have a Website. Please feel free to visit our site. Thank you for sharing.
    Be Your Own Boss! If you're looking for a change in your work prospects, then let's prepare for your career from here!!!
    Self Employment | Women Development | Information Technology | Engineering Courses

    ReplyDelete