Wednesday, March 6, 2013

Read csv file and import its data into List(object) with Linq
 
           var arrTitle = File.ReadAllLines(csvFileFolderPath)
                                .Select(x => x.Split(','))
                                .First();

            List lstUser = File.ReadAllLines(csvFileFolderPath)
                                                .Select(x => x.Split(','))
                                                .Skip(1)
                                                .Select(x =>
                                                     new Users
                                                     {
                                                         USERID = x[0],
                                                         LASTNAME = x[1],
                                                         FIRSTNAME = x[2],
                                                         PASSWORD = x[3]
                                                     }).ToList ();


 Read csv file and import its data into Datatable with Linq

            DataTable dt = new DataTable();

            var c1 = File.ReadAllLines(csvFileFolderPath)
                                    .Select(x => x.Split(','))
                                    .First().ToArray();

            var col = from cl in c1
                        select new DataColumn(cl);

            dt.Columns.AddRange(col.ToArray());

            var tableData = File.ReadAllLines(csvFileFolderPath)
                                .Select(x => x.Split(','))
                                .Skip(1)
                                .ToList();

            (from st in tableData
                    select dt.Rows.Add(st)).ToList();


Class File:

Public class Users
{
      public virtual string USERID { get; set; }
      public virtual string LASTNAME { get; set; }
      public virtual string FIRSTNAME { get; set; }
      public virtual string PASSWORD { get; set; }
}


No comments: