[I just happened upon this one.. this is pretty cool (not sure how it performs, but then again you are probably only talking a few cycles difference)].
I typically parse command line arguments like this:
1: // Class/Namespace deleted for brevity
2: static void Main(string[] args)
3: { 4: bool AAArgumentExists = false;
5: foreach(string arg in args)
6: { 7: switch(arg)
8: { 9: case "-aa":
10: AAArgumentExists = false;
11: break;
12: // Additional cases follow
13: }
14: }
15: }
Today, I just started thinking about this code... I really don't like it. It doesn't really evoke what I want to say. I want my code to say "does such and such argument exist in the string array."
Using LINQ we get a cleaner (in my opinion) variation of the above and it "says" what I want it to "say."
1: // Class/Namespace deleted for brevity
2: static void Main(string[] args)
3: { 4: bool AAArgumentExists = (from arg in args
5: where arg == "-aa"
6: select arg != "").FirstOrDefault();
7: }
Of course something else I tend to do is have an argument for passing in a date value (just something I seem to run into on a regular basis). Here's the code snippet to do that (I wish it were a little more terse... but I'm still a newbie to LINQ).
1: DateTime RunDate;
2: String RunDateString = (from arg in args
3: where DateTime.TryParse(arg, out RunDate)
4: select arg).FirstOrDefault();
5: if (RunDateString == null || RunDateString == "")
6: RunDate = DateTime.MinValue; /* Or whatever default value you want to use */
BTW, the above technique could be applied to a number of other data types.
Print | posted on Monday, November 26, 2007 8:19 AM