IEnumerable - implementing using GetEnumerator from local variable

匆匆过客 提交于 2019-12-25 03:11:09

问题


I'm newb with generics/iterators/enumerators etc.

I have code, it keeps field number (int) and error mesages (List string) for each field:

  public class ErrorList : IEnumerable // ?
  {
        private Dictionary <int, List<string>> errorList;

        // ...
  }

How to make this class work with foreach loop? I wanna use GetEnumerator form Dictionary, but how should i do this?


回答1:


You could simply provide a public GetEnumerator method:

public class ErrorList
{
    private Dictionary<int, List<string>> errorList = new Dictionary<int, List<string>>();

    ... some methods that fill the errorList field

    public IEnumerator<KeyValuePair<int, List<string>>> GetEnumerator()
    {
        return errorList.GetEnumerator();
    }
}

and now assuming you have an instance of ErrorList:

var errors = new ErrorList();

you can loop through them:

foreach (KeyValuePair<int, List<string>> item in errors)
{
    ...
}



回答2:


Dictionary implements IEnumerable<KeyValuePair<TKey, TValue>>, so this works:

foreach (KeyValuePair<Int, List<String>> kvp in errorList) {
    var idx = kvp.Key;
    var vals = kvp.Value;
    // ... do whatever here
}



回答3:


You can simply return errorList.GetEnumerator().



来源:https://stackoverflow.com/questions/9844159/ienumerable-implementing-using-getenumerator-from-local-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!