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

后端 未结 30 2316
刺人心
刺人心 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:18

    How about something like this? Note that myDelimitedString may be null if myEnumerable is empty.

    IEnumerator enumerator = myEnumerable.GetEnumerator();
    string myDelimitedString;
    string current = null;
    
    if( enumerator.MoveNext() )
        current = (string)enumerator.Current;
    
    while( null != current)
    {
        current = (string)enumerator.Current; }
    
        myDelimitedString += current;
    
        if( enumerator.MoveNext() )
            myDelimitedString += DELIMITER;
        else
            break;
    }
    

提交回复
热议问题