Rockford .Net User Group

The premier .Net User Group in the Northern Illinois Area
Welcome to Rockford .Net User Group Sign in | Join | Help
in Search

Searching CSV file using LINQ

Last post 10-14-2007, 8:56 PM by Ross Albertson. 0 replies.
Sort Posts: Previous Next
  •  10-14-2007, 8:56 PM 94

    Searching CSV file using LINQ

    Here is a simple C# program using LINQ to search an Excel comma-separated file:

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

    namespace CsvParse1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string name;
                bool found = false;

                Console.Write("Enter name: ");
                name = Console.ReadLine();
                string line;
                StreamReader r = File.OpenText(@"G:\projectdata\Book1.csv");
                do
                {
                    line = r.ReadLine();
                    if (line != null)
                    {
                        var dataline =
                            from d in line.Split(',')
                            where d == name
                            select line;

                        foreach (string s in dataline)
                        {
                            string[] data = s.Split(',');
                            found = true;
                            Console.WriteLine("The e-mail address is {0}", data[1]);
                        }
                    }
                } while (line != null);
                if (!found)
                    Console.WriteLine("No entry for {0}", name);
            }
        }
    }
    This program searches the file for a line with a string matching the name given by the user. The data file uses the format

    name,e-mail address

    I don't know if this code will compile on Visual Studio 2005; I used Visual Studio 2008 Beta 2. If I used Split to parse the file into an array of objects, I could have written

    var addresses =
         from d in data
         where d.Name == name
         select d.E_MailAddress;

    foreach (var a in addresses)
       Console.WriteLine ("Found e-mail address {0}", a);

    If you get brave and install the beta, let me know, and tell me what you do with LINQ.

    Ross

     

     


    Lay a .NET over the world
View as RSS news feed in XML
Powered by Community Server, by Telligent Systems