2010-06-15 193 views
2

迭代数组并不是一个问题,但是如果我只想在调用该方法时只增加数值,该怎么办?遍历数组

林甚至不知道这会工作,但有没有这样做的更简单的方法这个

int counter; 
    string[] myArray = {"foo", "bar", "something", "else", "here"}; 

    private string GetNext() 
    { 
     string myValue = string.Empty; 

     if (counter < myArray.Length) { 
      myValue = myArray [counter]; 
     } else { 
      counter = 0; 
     } 

     counter++; 

     return myValue; 
    } 
+0

我不知道我完全理解这个问题。 “我只想在方法被调用时才增加?” – Meiscooldude 2010-06-15 20:17:19

+0

不确定我看到你真正要求的 - 除了初始化语句,除非有人打电话给你的方法,否则这些都不会被调用。除非你担心有人可以修改GetNext函数的调用之间的计数器或数组内容... – 2010-06-15 20:19:38

回答

5

你需要的是一个迭代

private IEnumerable<String> myEnumarable() 
{ 
    foreach(string i in myArray) 
    { 
     yield return i; 
    } 
} 

但是只调用myArray.GetEnumerator复位();具有相同的效果。

您可以使用它通过

string[] myArray = { "foo", "bar", "something", "else", "here" }; 
IEnumerator<String> myEnum; 

private string GetNext() //Assumes there will be allways at least 1 element in myArray. 
{ 
    if(myEnum == null) 
     myEnum = myArray.GetEnnumerator(); 
    if(!myEnum.MoveNext()) 
    { 
     myEnum.Reset(); 
     myEnum.MoveNext(); 
    } 
    return myEnum.Current; 
} 
2

如果我理解你想要做什么,我相信所有你需要做的就是调用的GetEnumerator( )方法。枚举器对象具有MoveNext()方法,该方法将移至列表中的下一个项目,如果它工作则返回true,如果没有则返回false。你读与Current财产枚举值,并且可以将计数器为0与Reset

3

你可以代替试试这个:

private string GetNext() 
{ 
    string result = myArray[counter]; 
    counter = (counter + 1) % myArray.Length; 
    return result; 
} 

您的代码,其中“富”只返回第一次的错误。

 
foo 
bar 
something 
else 
here 
       <-- oops! 
bar 
something 
else 
here 
2

你发布的例子基本上是一个枚举器的实现,所以是的,它会工作。

string[] _array = {"foo", "bar", "something", "else", "here"}; 

IEnumerable<String> GetEnumarable() 
{ 
    foreach(string i in _array) 
     yield return i; 
} 

如果你想用一个自定义的数据结构来做到这一点还是希望把更多的逻辑,当移动到下一个元素(即延迟加载,流数据),可以实现IEnumerator接口自己。

public class EnumeratorExample : IEnumerator 
{ 
    string[] _array; 

    // enumerators are positioned before the first element 
    // until the first MoveNext() call. 
    int position = -1; 

    public EnumeratorExample(string[] array) 
    { 
     _array = list; 
    } 

    public bool MoveNext() 
    { 
     ++position; 
     return (position < _array.Length); 
    } 

    public void Reset() 
    { 
     position = -1; 
    } 

    object IEnumerator.Current 
    { 
     get { return Current; } 
    } 

    public string Current 
    { 
     get 
     { 
      try 
      { 
       return _array[position]; 
      } 
      catch (IndexOutOfRangeException) 
      { 
       throw new InvalidOperationException("Enumerator index was out of range. Position: " + position + " is greater than " + _array.Length); 
      } 
     } 
    } 
} 

参考
- IEnumerable Interface

0
int x=0; 
while (x<myArray.length){ 
    if(condition){ 
     x++; 
     system.out.print(myArray[x]); 
    } 
}