How do you get the index of the current iteration

2018-12-31 12:45发布

Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?

For instance, I currently do something like this depending on the circumstances:

int i=0;
foreach (Object o in collection)
{
    // ...
    i++;
}

标签: c# foreach
30条回答
步步皆殇っ
2楼-- · 2018-12-31 13:15

I just had this problem, but thinking around the problem in my case gave the best solution, unrelated to the expected solution.

It could be quite a common case, basically, I'm reading from one source list and creating objects based on them in a destination list, however, I have to check whether the source items are valid first and want to return the row of any error. At first-glance, I want to get the index into the enumerator of the object at the Current property, however, as I am copying these elements, I implicitly know the current index anyway from the current destination. Obviously it depends on your destination object, but for me it was a List, and most likely it will implement ICollection.

i.e.

var destinationList = new List<someObject>();
foreach (var item in itemList)
{
  var stringArray = item.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);

  if (stringArray.Length != 2)
  {
    //use the destinationList Count property to give us the index into the stringArray list
    throw new Exception("Item at row " + (destinationList.Count + 1) + " has a problem.");
  }
  else
  {
    destinationList.Add(new someObject() { Prop1 = stringArray[0], Prop2 = stringArray[1]});
  }
}

Not always applicable, but often enough to be worth mentioning, I think.

Anyway, the point being that sometimes there is a non-obvious solution already in the logic you have...

查看更多
回忆,回不去的记忆
3楼-- · 2018-12-31 13:16

I don't think this should be quite efficient, but it works:

@foreach (var banner in Model.MainBanners) {
    @Model.MainBanners.IndexOf(banner)
}
查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 13:17

Why foreach ?!

The simplest way is using for instead of foreach if you are using List .

for(int i = 0 ; i < myList.Count ; i++)
{
    // Do Something...
}

OR if you want use foreach :

foreach (string m in myList)
{
     // Do something...       
}

you can use this to khow index of each Loop :

myList.indexOf(m)
查看更多
骚的不知所云
5楼-- · 2018-12-31 13:17

Better to use keyword continue safe construction like this

int i=-1;
foreach (Object o in collection)
{
    ++i;
    //...
    continue; //<--- safe to call, index will be increased
    //...
}
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 13:18

This is how I do it, which is nice for its simplicity/brevity, but if you're doing a lot in the loop body obj.Value, it is going to get old pretty fast.

foreach(var obj in collection.Select((item, index) => new { Index = index, Value = item }) {
    string foo = string.Format("Something[{0}] = {1}", obj.Index, obj.Value);
    ...
}
查看更多
深知你不懂我心
7楼-- · 2018-12-31 13:20

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

  • MoveNext()
  • Current

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

Obviously, the concept of an index is foreign to the concept of enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

查看更多
登录 后发表回答