Gero
Gero

Reputation: 13563

How to skip a specific position within a for each loop in c sharp?

List<string> liste = new List<String> 
        {
            "A","B","C","D"
        };

        foreach (var item in liste)
        {
            System.Diagnostics.Debug.WriteLine(item.ToString());
        }

        for (int i = 0; i < liste.Count; i++)
        {
            if (i == 0)
                continue;
            System.Diagnostics.Debug.WriteLine(liste[i].ToString());
        }

How do i skip a specific position in a foreach loop? I do not want to evaluate any values, but just skip the position x.

It has to be a specific position. One could choose position 0 or maybe position 7.

Upvotes: 12

Views: 27249

Answers (5)

angrifel
angrifel

Reputation: 734

You should try using the enhanced version of the Where extension method that allows you to filter on item and index.

Check the reference. http://msdn.microsoft.com/en-us/library/bb549418.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Verbatim list");
            List<string> list = new List<String> { "A","B","C","D" };

            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }

            Console.WriteLine("Filtered list");
            int itemToSkip = 2;
            foreach (var item in list.Where((item, index) => index != itemToSkip))
            {
                Console.WriteLine(item.ToString());
            }

            Console.ReadKey();
        }
    }
}

This will give you the following output.

Verbatim list
A
B
C
D
Filtered list
A
B
D

Upvotes: 1

Ritch Melton
Ritch Melton

Reputation: 11608

I love list's .ForEach, here's my take using @Elian's .SkipAt(n) and .ForEach:

var list = new List<String> { "A", "B", "C", "D" };
list = list.SkipAt(1).ToList();
list.ForEach(Debug.WriteLine);

Upvotes: 1

Elian Ebbing
Elian Ebbing

Reputation: 19057

It is very easy to skip the first item in the list:

foreach(var item in list.Skip(1))
{
    System.Diagnostics.Debug.WriteLine(item.ToString());
}

If you want to skip any other element at index n, you could write this:

foreach(var item in list.Where((a,b) => b != n))
{
    System.Diagnostics.Debug.WriteLine(item.ToString());
}

In this example I use a lambda expression that takes two arguments: a and b. Argument a is the item itself, while argument b is the index of the item.

The relevant pages on MSDN that describe these extension methods are:

You could even write your own extension method that allows you to skip an element in a list:

public static class MyEnumerableExtensions
{
    public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> list, int index)
    {
        var i = 0;

        foreach(var item in list) 
        {
            if(i != index)
                yield return item;

            i++;
        }
    }
}

This will allow you to write something like this to skip an item:

foreach(var item in list.SkipAt(2))
{
    System.Diagnostics.Debug.WriteLine(item.ToString());
}

Upvotes: 26

James
James

Reputation: 7543

A foreach loop iterates over a collection that implements IEnumerable. The enumerator exposes the current item and a method to move onto the next item - it has no concept of an index.

You could always do:

var i = 0;
foreach (var item in liste) {
  if (i++ == skip) continue;
  Debug.WriteLine(item.ToString());
}

But this seems unnecessarily contrived. If you need an index, go with a for loop.

The other option is to remove the undesired item from the List before iterating:

foreach (var item in liste.Take(n-1).Union(liste.Skip(n))) {
  Debug.WriteLine(item.ToString());
}

Upvotes: 1

SpeedBirdNine
SpeedBirdNine

Reputation: 4676

To skip a position inside the foreach loop, one option is that you can skip the action inside the foreach loop by using an if statement, like

foreach(var item in liste)
{
    if (item != 'X')
    {
        //do something
    }
}

But i am waiting for better solutions

Upvotes: 0

Related Questions