English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

LINQ 변환 연산자

LINQ의 Conversion 연산자는 시퀀스(집합)의 요소 타입을 변환할 수 있습니다. 변환 연산자는 세 가지로 나뉩니다:As연산자(AsEnumerable와 AsQueryable),To연산자(ToArray, ToDictionary, ToList 및 ToLookup)과변환연산자(Cast와 OfType).

다음 표는 모든 변환 연산자를 나열합니다.

메서드설명
AsEnumerable

입력 시퀀스를 IEnumerable < T>로 반환합니다

AsQueryable

IEnumerableto를 IQueryable로 변환하여 원격 쿼리 제공자를 모의합니다

Cast

비 Generics 콜렉션을 Generics 콜렉션으로 변환합니다 (IEnumerable로부터 IEnumerable)

OfType지정된 타입에 따라 집합을 필터링합니다
ToArray집합을 배열로 변환합니다
ToDictionary

키 선택자 함수에 따라 요소를 Dictionary에 삽입합니다

ToList

집합을 List로 변환합니다

ToLookup요소를 Lookup<TKey,TElement>에 그룹화합니다

AsEnumerable와 AsQueryable 메서드

AsEnumerable와 AsQueryable 메서드는 각각 원본 객체를 IEnumerable <T> 또는 IQueryable <T>로 변환하거나 변환합니다.

다음 예제를 보세요:

class Program
{
    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-time type: {0}", typeof(T).Name);
        Console.WriteLine("실제 타입: {0}", obj.GetType().Name);
    }
    static void Main(string[] args)
    {
        Student[] studentArray = { 
                new Student() { StudentID = 1, StudentName = "John", Age = 18 }
                new Student() { StudentID = 2, StudentName = "Steve",     Age = 21 }
                new Student() { StudentID = 3, StudentName = "Bill",     Age = 25 }
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 31 }
            }   
            
        ReportTypeProperties(studentArray);
        ReportTypeProperties(studentArray.AsEnumerable());
        ReportTypeProperties(studentArray.AsQueryable());   
    }
}
출력:
Compile-타입 시간: Student[]
실제 타입: Student[]
Compile-타입 시간: IEnumerable`1
실제 타입: Student[]
Compile-time type: IQueryable`1
실제 타입: EnumerableQuery`1

위 예제와 같이, AsEnumerable와 AsQueryable 메서드는 각각 컴파일 시간 타입을 IEnumerable와 IQueryable로 변환합니다.

Cast

Cast의 작용은 AsEnumerable<T>와 동일합니다. 그것은 원본 객체를 IEnumerable<T>로 강제 변환합니다.

class Program
{
    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-time type: {0}", typeof(T).Name);
        Console.WriteLine("실제 타입: {0}", obj.GetType().Name);
    }
    static void Main(string[] args)
    {
        Student[] studentArray = { 
                new Student() { StudentID = 1, StudentName = "John", Age = 18 }
                new Student() { StudentID = 2, StudentName = "Steve",     Age = 21 }
                new Student() { StudentID = 3, StudentName = "Bill",     Age = 25 }
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 31 }
            }   
         
        ReportTypeProperties(studentArray);
        ReportTypeProperties(studentArray.Cast<Student>());
    }
}
출력:
Compile-타입 시간: Student[]
실제 타입: Student[]
Compile-타입 시간: IEnumerable`1
실제 타입: Student[]
Compile-타입 시간: IEnumerable`1
실제 타입: Student[]
Compile-타입 시간: IEnumerable`1
실제 타입: Student[]

studentArray.Cast<Student>()와 (IEnumerable<Student>)studentArray은 같지만, Cast<Student>()는 더 읽기 쉽습니다.

To 연산자: ToArray(), ToList(), ToDictionary()

명칭에서 알 수 있듯이, ToArray(), ToList(), ToDictionary() 메서드의 원본 객체 변환은 각각 배열, 목록 또는 딕셔너리입니다.

To 연산자는 쿼리를 강제합니다. 그것은 원격 쿼리 제공자가 쿼리를 실행하고 기본 데이터 소스(예: SQL Server 데이터베이스)에서 결과를 가져옵니다.

IList<string> strList = new List<string>() { 
                                            "One", 
                                            "Two", 
                                            "Three", 
                                            "Four", 
                                            "Three" 
                                            }
string[] strArray = strList.ToArray<string>();// 리스트를 배열로 변환하다
IList<string> list = strArray.ToList<string>(); // 배열을 목록으로 변환합니다

ToDictionary - 제네릭 리스트를 제네릭 딕셔너리로 변환하다:

IList<Student> studentList = new List<Student>() { 
                    new Student() { StudentID = 1, StudentName = "John", age = 18 }
                    new Student() { StudentID = 2, StudentName = "Steve",  age = 21 }
                    new Student() { StudentID = 3, StudentName = "Bill",  age = 18 }
                    new Student() { StudentID = 4, StudentName = "Ram" , age = 20 } ,
                    new Student() { StudentID = 5, StudentName = "Ron" , age = 21 } 
                }
//아래는 목록을 딕셔너리로 변환합니다. StudentId가 키입니다.
IDictionary<int, Student> studentDict = 
                                studentList.ToDictionary<Student, int>(s => s.StudentID); 
foreach(var key in studentDict.Keys)
	Console.WriteLine("Key: {0}, Value: {1} 
                                key, (studentDict[key] as Student).StudentName);
출력:
Key: 1, Value: John
Key: 2, Value: Steve
Key: 3, Value: Bill
Key: 4, Value: Ram
Key: 5, Value: Ron

아래 그림은 위 예제의 studentDict이 어떻게 key를 포함하고 있는지 보여줍니다.-value 쌍, key는 StudentID, value는 Student 객체입니다.

LINQ-ToDictionary 연산자