Best way to detect forat, last and middle array elements

Saga 426 Reputation points
2022-05-19T15:49:02.413+00:00

Hi all,

I have a string array: MyStringArray. I need to distinguish between the first, last and middle elements.

Currently, this is what I am doing:

           string[] MyStringArray = { "A", "B", "C", "D", "Z" };

            for (int i = 0; i < MyStringArray.Length; i++)
            {

                if (i == 0)
                {
                    //Do stuff for first element.
                    MessageBox.Show("First element: " + MyStringArray[i]);
                }
                else
                if (i < MyStringArray.Length - 1)
                {
                    //Do stuff for middle elements.
                    MessageBox.Show("Middle element: " + MyStringArray[i]);
                }
                else
                {
                    //Do stuff for last element.
                    MessageBox.Show("Last element: " + MyStringArray[i]);
                }

            }

This works, but I want to ask whether there is a better way to accomplish the same functionality. Thank your for your time. Saga

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,307 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.5K Reputation points
    2022-05-19T16:10:53.487+00:00

    Try this code:

    //Do stuff for first element.
    MessageBox.Show( "First element: " + MyStringArray.First( ) );
    
    for( int i = 1; i < MyStringArray.Length - 1; i++ )
    {
        //Do stuff for middle elements.
        MessageBox.Show( "Middle element: " + MyStringArray[i] );
    }
    
    //Do stuff for last element.
    MessageBox.Show( "Last element: " + MyStringArray.Last( ) );
    

    It assumes that the array is not empty.

    An alternative for middle elements:

    foreach( var s in MyStringArray.Skip( 1 ).Take( MyStringArray.Length - 2 ) )
    {
        //Do stuff for middle elements.
        MessageBox.Show( "Middle element: " + s );
    }
    

    In case of modern C# in .NET 6:

    foreach( var s in MyStringArray[1..^1] )
    {
        //Do stuff for middle elements.
        MessageBox.Show( "Middle element: " + s );
    }
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful