프로그래밍/.NET2013. 2. 23. 18:06

IEnumerable, IEnumerator

컬렉션을 단순히 반복하고 지원해줍니다.


IEnumerable 메서드

 GetEumerator()

 컬렉션을 반복하는 열거자를 반환 


IEnumerator 메서드

 MoveNext() 

 열거자를 컬렉션의 다음 요소로 이동 

 Reset()

 컬렉션의 첫 번째 요소 앞의 초기 위치에 열거자를 설정 


IEnumerator 예제

Program.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Program
{
    static void Main(string[] args)
    {
        // IEnumerator 를 이용한 순방향 검색
 
        /// <summary>
        /// string 객체에는 IEnumerable 인터페이스가 구현되어있습니다.
        /// </summary>
        string[] strList = { "jeong", "kang", "won", "lee", "hee" };
 
        IEnumerator e = strList.GetEnumerator();
 
        while (e.MoveNext())
        {
            Console.WriteLine(e.Current);
        }
 
        //Console.WriteLine(e.Current);       // 이미 열거가 완료되어 에러
             
        e.Reset();
        e.MoveNext();
        Console.WriteLine(e.Current);       // "jeong" 출력
 
        Console.ReadLine();
    }
}



IEnumerable(Linq) 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Program
{
    static void Main(string[] args)
    {
        // Linq
 
        /// <summary>
        /// string 객체에는 IEnumerable 인터페이스가 구현되어있습니다.
        /// </summary>
        string[] strList = { "jeong", "kang", "won", "lee", "hee" };
 
        // 조건 : 글자수가 3개 이하인 글자
             
        //IEnumerable<string> enumerable = strList.Where(str => str.Length <= 3);
        IEnumerable<string> enumerable = from str in strList where str.Length <= 3 select str;
 
 
        IEnumerator<string> e = enumerable.GetEnumerator();
 
        while (e.MoveNext())
        {
            Console.WriteLine(e.Current);
        }
 
        Console.ReadLine();
 
    }
}
</string></string></string>



Posted by 건깡