LINQ to text file

CodeKeep C# Feed Maggio 5th, 2008

Description: Use LINQ to read

Link: http://www.codekeep.net/snippets/a48cd7ec-e571-4d20-8995-cd35186a8d0e.aspx

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

namespace LinqToText
{
  public static class StreamReaderSequence
  {
    public static IEnumerable<string> Lines(this StreamReader source)
    {
      String line;

      if (source == null)
          throw new ArgumentNullException("source");
      while ((line = source.ReadLine()) != null)
      {
        yield return line;
      }
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      StreamReader sr = new StreamReader("TextFile.txt");

      var t1 =
        from line in sr.Lines()
        let items = line.Split(',')
        where ! line.StartsWith("#")
        select String.Format("{0}{1}{2}",
            items[1].PadRight(16),
            items[2].PadRight(16),
            items[3].PadRight(16));

      var t2 =
        from line in t1
        select line.ToUpper();

      foreach (var t in t2)
        Console.WriteLine(t);

      sr.Close();
    }
  }
}

  • .NET
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Comments are closed.

Trackback URI |