HOWTO · Csharp
C#에서 목록을 IEnumerable로 변환
List 데이터 구조가 이미 IEnumerable 인터페이스를 구현하고 있기 때문에 List를 IEnumerable로 변환 할 필요가 없지만 여전히 일부 메서드를 사용하여 List를 IEnumerable 데이터 구조로 캐스팅 할 수 있습니다.
이 페이지의 내용
이 자습서에서는 C#에서 목록을IEnumerable로 변환하는 방법에 대해 설명합니다.
C#에서as키워드를 사용하여 목록을 IEnumerable로 변환
C#에서as키워드를 사용하여List데이터 구조를IEnumerable데이터 구조로 변환 할 수 있습니다. 다음 예를 참조하십시오.
using System;
using System.Collections.Generic;
namespace list_to_ienumerable {
class Program {
static void Main(string[] args) {
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = ilist as IEnumerable<int>;
foreach (var e in enumerable) {
Console.WriteLine(e);
}
}
}
}
출력:
1
2
3
4
5
위의 코드에서 우리는 C#에서as키워드를 사용하여 정수ilist의List를 정수enumerable의IEnumerable로 변환했습니다.
C#의 Typecasting 메서드를 사용하여 목록을 IEnumerable로 변환
또한 typecasting 메소드를 사용하여List데이터 유형의 객체를IEnumerable데이터 유형의 객체에 저장할 수 있습니다 (다음 코드 예제 참조).
using System;
using System.Collections.Generic;
namespace list_to_ienumerable {
class Program {
static void Main(string[] args) {
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = (IEnumerable<int>)ilist;
foreach (var e in enumerable) {
Console.WriteLine(e);
}
}
}
}
출력:
1
2
3
4
5
위의 코드에서 우리는 C#의 typecasting 메서드를 사용하여 정수ilist의List를 정수enumerable의IEnumerable로 변환했습니다.
C#의 LINQ 메서드를 사용하여 목록을 IEnumerable로 변환
LINQ는 SQL 쿼리 기능을 C#의 데이터 구조와 통합합니다. LINQ의AsEnumerable()함수를 사용하여 목록을 C#의IEnumerable로 변환 할 수 있습니다. 다음 코드 예제는 C#에서 LINQ의AsEnumerable()함수를 사용하여List데이터 구조를IEnumerable데이터 구조로 변환하는 방법을 보여줍니다.
using System;
using System.Collections.Generic;
using System.Linq;
namespace list_to_ienumerable {
class Program {
static void Main(string[] args) {
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = ilist.AsEnumerable();
foreach (var e in enumerable) {
Console.WriteLine(e);
}
}
}
}
출력:
1
2
3
4
5
위 코드에서 우리는 C#의ilist.AsEnumerable()함수를 사용하여 정수ilist의List를 정수enumerable의IEnumerable으로 변환했습니다.