Linq to CSV
Linq to CSV
This post is about something old, something I should have posted about a long time ago. A few years ago I had to use a CSV file as a data source for some process. I had forgotten all about it until recently when I was looking through some old projects, they definitely brought back some memories.
I do remember thinking there has to be a better way to access a CSV file more like a database and have it populate an object. I started to get my frame of mind all set to come up with a solution when I thought how dumb it is to re-invent the wheel. So I did a search first, and found the LinqToCsv package.
What is LinqToCsv
LinqToCsv is a neat nuget package you can install to your project. You have to do some minimal setup, but it is worth it. LinqToCsv allows you to read in the data from a CSV file or really most delimited files, and put that data into an IEnumerable of some class.
Since you now have the CSV’s data in a nice IEnumerable of some class you can easily iterate over it and access the data in a more object oriented way. Sounds neat doesn’t it!
A Simple Demo
Lets create a simple demo of how to use it. For this demo I’m just going to use Visual Studio Code and the .NET CLI. First I’m going to create a new console project. Of course you can do this in full on Visual Studio. For those who just want to try Visual Studio Code but are not sure how to create a new console application please see this tutorial.
Now that we have our new console application created we need to add the nuget package. For our Visual Studio Code users you should open the integrated terminal and run dotnet add package LinqToCsv. For Visual Studio types you can run this from your package manager; Install-Package LinqToCsv -Version 1.5.0.
You need a CSV file in your project. How can we use LinqToCsv without a CSV. I used the below text to create somecolors.csv.
Since this is such a small and simple demo I’m just going to put it into a single Gist. Please note, that the class I created to hold my CSV data is in the same file as the program class.
If everything is setup properly you should get this output when you run it. Well, those of you in Visual Studio may want to add a Console.ReadLine to it. In Visual Studio Code it will write it to the integrated terminal when you use dotnet run.
red has a hex of #ff0000 and RGB of 255,0,0
yellow has a hex of #ffff00 and RGB of 255,255,0
green has a hex of #00800 and RGB of 0,128,0
blue has a hex of #0000ff and RGB of 0,0,255
purple has a hex of #800080 and RGB of 128,0,128
aqua has a hex of #00ffff and RGB of 0,255,255
Here are some links related to LinqToCsv.