5,661,954 members and growing! (14,332 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » LINQ » General     Intermediate License: The Code Project Open License (CPOL)

LINQ to Text or CSV Files - Part 1

By Alomgir Miah Abdul

A simple utility to LINQ against CSV files
C# 3.0, C#.NET, .NET 3.5, .NET 3.0, LINQ, Architect, Dev

Posted: 11 Oct 2008
Updated: 14 Nov 2008
Views: 4,865
Bookmarked: 35 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
25 votes for this Article.
Popularity: 6.24 Rating: 4.46 out of 5
1 vote, 4.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
6 votes, 24.0%
4
18 votes, 72.0%
5

Introduction

With the introduction of LINQ in C# 3.0, the life of a developer has become very easy when it comes to querying collections. In this article, I will show you a quick and easy way to query large CSV files.

Background

Imagine you have a very large CSV file. Loading the entire file into memory (e.g. DataSet) and querying it with LINQ would be a huge overhead. So I thought why not use StreamReader on the file instead.

Using the Code

I have implemented IEnumerable<string[]> and for every call to GetEnumerator, a line is read from CSV file. This class returns an enumerable string[].

public class TextFileReader : IEnumerable<string[]>
{
    private string _fileName = string.Empty;

    public TextFileReader(string fileName)
    {
        this._fileName = fileName;
    }

    #region IEnumerable<string[]> Members
  
    IEnumerator<string[]> IEnumerable<string[]>.GetEnumerator()
    {
        using (StreamReader streamReader = new StreamReader(this._fileName))
        {
            while (!streamReader.EndOfStream)
            {
                yield return streamReader.ReadLine().Split(new char[] { ',' });
            }
        }
    }

    #endregion
  
    #region IEnumerable Members
 
    IEnumerator IEnumerable.GetEnumerator()
    {
        IEnumerable<string[]> iEnumerable = this; 
        yield return iEnumerable.GetEnumerator();
    }
 
    #endregion
}

Using this class is very simple. Just initialize the class with the CSV file name and you are all set to LINQ it using standard operator. The following code shows how to query all the rows in the CSV file with the first column text starting with 'a'.

TextFileReader reader = new TextFileReader(@"Sample.txt");

var query = from it in reader
            where it[0].StartsWith("a")
            select new { Name = it[0], EmailAddress = it[1] };

foreach (var x in query)
{
    Console.WriteLine(String.Format("Name={0} EmailAddress = {1}", 
    x.Name, x.EmailAddress));
}

Points of Interest

Well, this may not be the best way to implement this. I am also into the process of learning LINQ. Please feel free to give your comments or suggestions. In my next article, I will show you how to write a custom query provider for CSV files. Please stay tuned.

History

  • 11th October, 2008: Initial post
  • 14th Novermber, 2008: Updates source and article

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Alomgir Miah Abdul



Location: United States United States

Other popular LINQ articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
GeneralCSV and field separatormemberTobiasP2:52 14 Oct '08  
GeneralElegant!memberPat Tormey2:06 14 Oct '08  
GeneralJust a comment...memberSeth Morris23:17 13 Oct '08  
GeneralRe: Just a comment...memberTobiasP4:07 14 Oct '08  
GeneralRe: Just a comment...memberAlomgir Abdul Miah5:00 14 Oct '08  
GeneralExcellent, but how about...memberJohn O'Halloran18:23 13 Oct '08  
GeneralRe: Excellent, but how about...memberAlomgir Abdul Miah18:55 13 Oct '08  
GeneralGreat article!!!memberAchintya Jha15:16 12 Oct '08  
GeneralGreat article!memberIamBond0073:25 12 Oct '08  
GeneralNice!memberDale Visser2:32 12 Oct '08  
GeneralRe: Nice!memberAlamgir Miah7:24 12 Oct '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 Nov 2008
Editor: Sean Ewington
Copyright 2008 by Alomgir Miah Abdul
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project