"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Tuesday, February 12, 2013

convert datatable to generic list in c#

convert datatable to generic list in c#




  public class Man
    {
        private string shirt;
        public string Shirt { get { return shirt; } set { shirt = value; } }
        private int trouser;
        public int Trouser { get { return trouser; } set { trouser = value; } }
        private bool watch;
        public bool Watch { get { return watch; } set { watch = value; } }
        private DateTime date;
        public DateTime Date { get { return date; } set { date = value; } }
    }


protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable
            {
                Columns ={
                {"shirt",typeof(string)},
                {"trouser",typeof(int)},
                {"watch",typeof(bool)},
                {"Date",typeof(DateTime)}
            }
            };
            dt.Rows.Add("White", 1, true, DateTime.Now);
            dt.Rows.Add("Black", 2, false, DateTime.UtcNow);
            dt.Rows.Add("Brown", 1, true, DateTime.Now);
            dt.Rows.Add("Gray", 1, false, DateTime.UtcNow);
            List<Man> mn = new List<Man>();
            mn = dt.AsEnumerable().Select(data => new Man() { Shirt = (string)data["shirt"], Trouser = (int)data["trouser"], Watch = (bool)data["watch"], Date = (DateTime)data["Date"] }).ToList<Man>();

        }


Now get ur out list at mn

If u had any trouble just ask, Happy to help u :)
Stay Tune...
Have a nice day... 'N happy Coding :)

No comments: