-1

Is there way to find out when I'm at the first and last loop on a foreach?

foreach(string str in list){
  if(str.isFirst(list) == true){...} 
  if(str.isLast(list) == true){...} 
}

^ Something like this?

Control Freak
  • 12,965
  • 30
  • 94
  • 145
  • 4
    i would use an indexed for loop for this. – jn1kk Sep 10 '14 at 21:57
  • 1
    A `foreach` knows only the current item. Btw, there are already very similar questions like http://stackoverflow.com/questions/4717120/c-sharp-how-to-get-last-time-in-foreach-statement – Tim Schmelter Sep 10 '14 at 21:58
  • As @TimSchmelter suggested following [answer](http://stackoverflow.com/a/4717161/477420) shows very good implementation of "is last" for `IEnumerable` which can easily be adapted to "is first". When implementing make sure to define what behavior you want for 0 and 1 cases. – Alexei Levenkov Sep 10 '14 at 22:20

5 Answers5

6
for (int i = 0; i < list.Length; i++)
{
    if (i == 0) 
    { 
        // is first iteration 
    }
    if (i >= list.Length - 1) 
    { 
        // is last iteration 
    }
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
1

Use a counter

int i = 0;
foreach(string str in list)
{
   if(i == 0) { /* first */ }
   if(i == list.Count - 1)  { /* last */ }
   i++;
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • Yeah, that would work. But if you're going to maintain counters, you might as well just use a `for` loop. – Robert Harvey Sep 10 '14 at 22:01
  • The way the question was worded, this is probably the best solution proposed thus far, although a standard `for` loop does make more sense. – user2366842 Sep 10 '14 at 22:02
1

The simplest way to check whether you are process the first or last item would be the following code :

void Process(string[] strings)
{
    for (int i = 0; i < strings.Length; i++)
    {
        var s = strings[i];

        bool isFirst = i == 0;
        bool isLast = i == strings.Length - 1;
    }
}
aybe
  • 15,516
  • 9
  • 57
  • 105
0

Alternative way

foreach(var kv in list.ToDictionary(k => list.IndexOf(k), v => v))
{
    if (kv.Key == 0) Console.WriteLine("First is {0}", kv.Value);
    if (kv.Key == list.Count - 1) Console.WriteLine("Last is {0}", kv.Value);
}

The best option is a for() cycle anyway

Sam
  • 2,950
  • 1
  • 18
  • 26
-1
bool first = true;    
foreach(string str in list)
{
  if(first) 
  {
      //do something
      first = false;
  } 
}
Enrico Sada
  • 909
  • 4
  • 9