This foreach is intended to look through a list and when a match is found it returns the next element. Can it be improved?
public static string GetCommandLineArg(string arg)
{
var doreturn = false;
foreach (var item in Environment.GetCommandLineArgs())
if (doreturn)
return item;
else if (arg == item)
doreturn = true;
return null;
}
The part I am concerned with is the returning of the next item.
The inner if statement is messy and the use of an extra variable seems unnecessary. Is there a simple function call or property which can be used with a foreach to return the next item?
Example: https://dotnetfiddle.net/pFc4dU
Approach with Linq
public static string GetCommandLineArg(string arg)
{
return Environment.GetCommandLineArgs().SkipWhile(x => x != arg).Skip(1).FirstOrDefault();
}
https://dotnetfiddle.net/zsIhtv
Does it have to be a forech loop? would it be simpler with for loop?
var items = Environment.GetCommandLineArgs();
for (int i = 0; i < items.Count(); i++)
{
var item = items[i];
if (arg == item && i < items.Count())
return items[i+1];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With