Ben
Ben

Reputation: 2533

First or Last element in a List<> in a foreach loop

I have a List<string> and I want to identify either the first or last element in the list so I can identify a different function to do with that item.

Eg.

foreach (string s in List)
{
    if (List.CurrentItem == (List.Count - 1))
    {
        string newString += s;
    }
    else
    {
        newString += s + ", ";
    }
}

How would I go about defining List.CurrentItem? Would a for loop be better in this situation?

Upvotes: 1

Views: 3107

Answers (4)

Parimal Raj
Parimal Raj

Reputation: 20595

You can use a linq based solution

Example :

var list = new List<String>();
list.Add("A");
list.Add("B");
list.Add("C");

String first = list.First();
String last = list.Last();
List<String> middle_elements = list.Skip(1).Take(list.Count - 2).ToList();

Upvotes: 1

Adriaan Stander
Adriaan Stander

Reputation: 166606

Rather make use of String.Join

Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.

It is a lot simpler.

Something like

        string s = string.Join(", ", new List<string>
        {
            "Foo",
            "Bar"
        });

Upvotes: 8

Devesh
Devesh

Reputation: 4560

you can use the counter like this

         int counter = 0 ;
         foreach (string s in List)
         {
               if (counter == 0) // this is the first element
                {
                  string newString += s;
                }
               else if(counter == List.Count() - 1) // last item
                {
                newString += s + ", ";
                }else{
                 // in between
               }
                counter++;
       }

Upvotes: 0

bitfiddler
bitfiddler

Reputation: 2115

Try something like this:

string newString = "";

foreach (string s in List)
{
  if( newString != "" )
    newString += ", " + s;
  else
    newString += s;
}

Upvotes: 0

Related Questions