Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this foreach be improved? [closed]

Tags:

c#

foreach

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

like image 607
Matt W Avatar asked Dec 22 '25 21:12

Matt W


2 Answers

Approach with Linq

public static string GetCommandLineArg(string arg)
{
    return Environment.GetCommandLineArgs().SkipWhile(x => x != arg).Skip(1).FirstOrDefault();
}

https://dotnetfiddle.net/zsIhtv

like image 134
fubo Avatar answered Dec 24 '25 10:12

fubo


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];
    }
like image 42
Adam Bilinski Avatar answered Dec 24 '25 09:12

Adam Bilinski