65

Say I have a foreach loop.

I have to do something with the first object of the loop that I don't have to do with any of the other objects.

How do I check if the item that's currently in the loop is the first object.

10 Answers 10

117

I like the Linq way, but without the Skip(1), this way you can also use it for the last item in a list and your code remains clean imho :)

foreach(var item in items)
{
    if (items.First()==item)
        item.firstStuff();

    else if (items.Last() == item)
        item.lastStuff();

    item.otherStuff();
}
2
  • 15
    I don't like this approach because it's not strictly accurate. If an item is present more than once, for example, and is also the first or last item, then you'll fire the first or last condition more than once. or if some items have equality, they can fire it more than once too. Dec 25, 2015 at 6:23
  • 3
    @Sahuagin Question is about testing item for is it first or not. If you clear the else if part, which means you are testing item for being only first or not, your rightful concerns will be soothed.
    – ErTR
    Jun 21, 2016 at 7:30
63

There are several ways that you could do that.

  1. Use a for loop instead
  2. Set a Boolean flag
  3. Use Linq to get the list.First() and then foreach over list.Skip(1)
41

Something like this:

bool first = true;

foreach(var item in items)
{
    if (first)
    {
        item.firstStuff();
        first = false;
    }
    item.otherStuff();
}
20

Here's a performant solution:

using (var erator = enumerable.GetEnumerator())
{
    if (erator.MoveNext())
    {
        DoActionOnFirst(erator.Current);

        while (erator.MoveNext())
            DoActionOnOther(erator.Current);
    }
}

EDIT: And here's a LINQ one:

if (enumerable.Any())
    {
        DoActionOnFirst(enumerable.First());

        foreach (var item in enumerable.Skip(1))
            DoActionOnOther(item);
    }

EDIT: If the actions on the items have signatures assignable to Func<TItem, TResult>, you can do:

enumerable.Select((item, index) => index == 0 ? GetResultFromFirstItem(item) : GetResultFromOtherItem(item));
5
  • 6
    While this technically satisfies the requirements, it is significantly less readable than using a 'first' flag to indicate as others have posted. Aug 24, 2010 at 3:28
  • 4
    @ Paul: It is more efficient, and I don't see why it is significantly less readable.
    – Ani
    Aug 24, 2010 at 3:31
  • Not sure how this is more efficient when compared to using a 'first' flag.
    – Babar
    Aug 24, 2010 at 5:50
  • 7
    @Babar With this solution there is no need to evaluate a variable on each iteration
    – Lukazoid
    Jun 12, 2015 at 16:16
  • For the LINQ answer this should be the correct answer as it is more elegant than using a flag.
    – bytedev
    Feb 12, 2018 at 15:10
6
bool first = true;
foreach(var foo in bar)
{
  if (first)
  {
    // do something to your first item
    first = false;
  }
  // do something else to the rest
}
2
  • grr, not quick enough! didn't see geofftnz's post.
    – Hamza
    Aug 24, 2010 at 3:25
  • 3
    it's the StackOverflow patented easy-question race :)
    – geofftnz
    Aug 24, 2010 at 3:32
6

In my opinion this is the simplest way

foreach (var item in list)
{
    if((list.IndexOf(item) == 0)
    {
        // first
    }
    // others
}
1
  • 9
    It may be the simplest way, but it is very expensive. If list is an arbitrary IEnumerable the complexity is within O(n) which is a lot of overhead to be performed in each iteration.
    – Pretasoc
    Jan 8, 2019 at 12:40
3

try this one

bool IsFirst = true;

foreach(DataRow dr in dt.Rows)
{
    if (IsFirst)
    {
        // do some thing
        IsFirst = false;
    }    
}
2

Can't think of anything but

var processedFirst = false;
foreach(var x in items) {
    if(!processedFirst) {
        ProcessFirst(x);
        processedFirst = true;
    }
2

This is more of a general solution for getting index along with each object in an array. Should work testing if it's the first.

        List<String> entries = new List<string>();
        entries.Add("zero");
        entries.Add("one");
        entries.Add("two");

        Dictionary<int, String> numberedEntries = new Dictionary<int, string>();
        int i = 0;
        entries.ForEach(x => numberedEntries.Add(i++, x));
        foreach (KeyValuePair<int, String> pair in numberedEntries) {
            Console.WriteLine(pair.Key + ": " + pair.Value);
        }

In this setup, the Key of the KeyValuePair is the index and the value is the object at that index, in my example a string, but any object could be placed there. It adds a little overhead, but can be used to determine any object in the list's index when needed.

1
  • Smells like Python's dict.__items__ I like it! Mar 6, 2012 at 23:22
1

You can also write:

foreach ((T item, bool isFirst) in items.Select((item, index) => (item, index == 0)))
{
    if (isFirst)
    {
        ...
    }
    else
    {
        ...
    }
}

If you need this a lot, you can write an extension method to replace the Select and make your code shorter.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.