Marco Dorantes' WebLog

"Computer science is no more about computers than astronomy is about telescopes" -Edsger W. Dijkstra

Argument processing and C# 2.0 iterators

Argument processing and C# 2.0 iterators

  • Comments 2

Sometime, you want to process this command-line argument:

C:\>aprogram arg0 arg1 @arg2 arg3 @arg4
arg0, arg1, arg3 are actual data to process whereas arg2 and arg4 are text file names where each text line inside is another actual data to process (aka response files).

Here is a way to convey such a processing using C# 2.0 iterators:
using System;
using System.IO;
using System.Collections;

class exe
{
  static void Main(string[] args)
  {
    foreach(string arg in GetArgs(args))
      process(arg);
  }

  static void process(string arg)
  {
    Console.WriteLine(arg);
  }

  static IEnumerable GetArgs(params string[] args)
  {
    foreach(string s in args)
    {
      if(s.StartsWith("@"))
        foreach(string sql in GetArgsInFile(s.Substring(1)))
          yield return sql;
      else
        yield return s;
    }
  }

  static IEnumerable GetArgsInFile(string filename)
  {
    using (StreamReader reader = File.OpenText(filename))
    {
      string line = reader.ReadLine();
      while (line != null)
      {
        foreach(string innerline in GetArgs(line))
          yield return innerline;
        line = reader.ReadLine();
      }
    }
  }
}



  • Sometimes, I just need to quickly send SQL queries or commands to a SQL database one by one or in...
Page 1 of 1 (2 items)
Leave a Comment
  • Please add 5 and 4 and type the answer here:
  • Post