Subscribe to Blog.Parse(typeof(PsychoCoder), Richard McCutchen);        RSS Feed
-----

Reading CSV file with LINQ in C#

Icon Leave Comment
Recently the question was posed on how to read a CSV (delimited) file with C# and LINQ, so I thought this was a fun question, so I set out to see what kind of solution I could come up with. I decided to use LINQ for this task. I created an Extension method for the StreamReader class. This method takes a StreamReader object (Well Duh PsychoCoder, of course it does). It then enumerates through the file and returns all the lines (delimiter in place).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

public static class LinqToText
{
	public static IEnumerable<string> GetAllLines(this StreamReader reader)
	{
		string line;

		//if not reader is supplied throw an Exception
		if (reader == null)
			throw new ArgumentNullException("reader");

		//otherwise we want to loop through the file and get all the curators
		while ((line = reader.ReadLine()) != null)
		{
			//return all the lines (which are enumerable)
			yield return line;
		}
	}
}



Now that I have this extension I can create a method that returns a generic list of the items in the file (You can use whatever you want to return it in, this example will use a generic list)

public static List<string> ReadCsvFile(string file)
{
	//create a generic list to hold the data
	List<string> c = new List<string>();
	try
	{
		//open the StreamReader and open the file
		using (StreamReader reader = new StreamReader(file, Encoding.Default))
		{
			//use the extension method GetAllLines for getting an enumerable
			//list of the items returned
			var str = from s in LinqToText.GetAllLines(reader)
						   select s;
			//loop through each and add it to the generic list
			foreach (string curator in str)
			{
				c.Add(curator);
			}

			return c;
		}
	}
	catch (IOException ex)
	{
		Console.WriteLine(ex.ToString());
		return c;
	}
}



So as you can see LINQ is a very powerful tool in the .Net Framework. Hope you enjoyed reading :)

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

July 2020

S M T W T F S
   1234
5678910 11
12131415161718
19202122232425
262728293031 

Recent Entries

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)