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.
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.
Something like this:
bool first = true;
foreach(var item in items)
{
if (first)
{
item.firstStuff();
first = false;
}
item.otherStuff();
}
bool first = true;
foreach(var foo in bar)
{
if (first)
{
// do something to your first item
first = false;
}
// do something else to the rest
}
Can't think of anything but
var processedFirst = false;
foreach(var x in items) {
if(!processedFirst) {
ProcessFirst(x);
processedFirst = true;
}
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));
There are several ways that you could do that.
try this one
bool IsFirst = true;
foreach(DataRow dr in dt.Rows)
{
if (IsFirst)
{
// do some thing
IsFirst = false;
}
}
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 their. It adds a little overhead, but can be used to determine any object in the list's index when needed.