Home
Manage Your Code
Snippet: LINQ to text file (C#)
Title: LINQ to text file Language: C#
Description: Use LINQ to read Views: 197
Author: Mark Henderson Date Added: 5/5/2008
Copy Code  
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Text;
5using System.IO;
6using System.Query;
7
8namespace LinqToText
9{
10  public static class StreamReaderSequence
11  {
12    public static IEnumerable<string> Lines(this StreamReader source)
13    {
14      String line;
15
16      if (source == null)
17          throw new ArgumentNullException("source");
18      while ((line = source.ReadLine()) != null)
19      {
20        yield return line;
21      }
22    }
23  }
24
25  class Program
26  {
27    static void Main(string[] args)
28    {
29      StreamReader sr = new StreamReader("TextFile.txt");
30
31      var t1 =
32        from line in sr.Lines()
33        let items = line.Split(',')
34        where ! line.StartsWith("#")
35        select String.Format("{0}{1}{2}",
36            items[1].PadRight(16),
37            items[2].PadRight(16),
38            items[3].PadRight(16));
39
40      var t2 =
41        from line in t1
42        select line.ToUpper();
43
44      foreach (var t in t2)
45        Console.WriteLine(t);
46
47      sr.Close();
48    }
49  }
50}
Notes
http://blogs.msdn.com/ericwhite/archive/2006/08/31/734383.aspx If you run this example with the following text file: #This is a comment 1,Eric,White,Writer 2,Bob,Jones,Programmer 3,Orville,Wright,Inventor 4,Thomas,Jefferson,Statesman 5,George,Washington,President It produces the following output. ERIC WHITE WRITER BOB JONES PROGRAMMER ORVILLE WRIGHT INVENTOR THOMAS JEFFERSON STATESMAN GEORGE WASHINGTON PRESIDENT