Wriju's BLOG

.NET, Cloud and everything

LINQ to CSV : Getting data the way you want

Getting data from CSV is one of the mostly used business in applications/tools development.


Here how we can do it in LINQ,


You have a table called Emp with the below details,


CREATE TABLE [dbo].[Emp](


      [Id] [int] IDENTITY(1,1) NOT NULL,


      [FirstName] [varchar](50) NOT NULL,


      [LastName] [varchar](50) NULL,


 CONSTRAINT [PK_Emp] PRIMARY KEY CLUSTERED


(


      [Id] ASC


)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]


) ON [PRIMARY]


Now you may want to get the CSV out of it. To do that you can save the query output to a .csv file.


The contents of that csv would look like,


1,Wriju,Ghosh


10,Writam,Ghosh


11,Debajyoti,Ghosh


12,Sumitra,Ghosh


82,Tupur,Sanyal


 


So when you get a single line you can Split() them with a comma (,). The code is very simple,


string[] allLines = File.ReadAllLines(@”E:\Temp\Emp.csv”);


 


var query = from line in allLines


            let data = line.Split(‘,’)


            select new


            {


                ID = data[0],


                FirstName = data[1],


                LastName = data[2]


            };


 


foreach (var s in query)


{


    Console.WriteLine(“[{0}] {1} {2}”, s.ID, s.FirstName, s.LastName);


}


Namoskar!!!