How do you get the index of the current iteration of a foreach loop?

后端 未结 30 2189
刺人心
刺人心 2020-11-22 07:05

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 iter

30条回答
  •  借酒劲吻你
    2020-11-22 07:32

    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();
    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...

提交回复
热议问题