Parsing Delimited Text Files with LINQ

A simple LINQ query can be used to parse delimited text files into a list of objects.

Consider a tab-delimited file named Data.txt that contains contact information.  Specifically,it contains Names, Phone Numbers, Birth Dates, and Email Addresses, like this:

Joe Smith    111-222-3333     1/1/1980
John Doe     444-555-6666     7/31/1970
Jane Doe     666-777-8888     4/25/1975

Assume that the following class exists:

class Contact
    public string Name { get; set; }
    public string Phone { get; set; }
    public string BirthDate { get; set; }
    public string Email { get; set; }

This LINQ query will produce a list of Contact objects that are populated with the information in the text file:

var contacts = from line in System.IO.File.ReadAllLines(@"Data.txt")
               let parts = line.Split(‘\t’)
               select new Contact
                   Name = parts[0],
                   Phone = parts[1],
                   BirthDate = parts[2],
                   Email = parts[3]

One Response to Parsing Delimited Text Files with LINQ

  1. Santa's Little Helper says:

    Thanks, saved some time and pain

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: