2008-09-04 5 views
10

다음 코드를 LINQPad에서 작동 시키려고하지만 var에 인덱스 할 수 없습니다. LINQ에서 var에 인덱스하는 방법을 아는 사람은 누구입니까?LINQ에서 var에 어떻게 인덱스합니까?

string[] sa = {"one", "two", "three"}; 
sa[1].Dump(); 

var va = sa.Select((a,i) => new {Line = a, Index = i}); 
va[1].Dump(); 
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' 

답변

21

는 의견은 유형 System.Collections.Generic.IEnumerable<T>의 표현 []와 색인을 적용 할 수 없습니다, 말했듯이. IEnumerable 인터페이스는 GetEnumerator() 메서드 만 지원합니다. 그러나 LINQ를 사용하면 확장 방법 ElementAt(int)을 호출 할 수 있습니다. -하지 인덱스 유형 두 경우 모두 selectVar에서

//works because under the hood the C# compiler has converted var to string[] 
var arrayVar = {"one", "two", "three"}; 
arrayVar[1].Dump(); 

//now let's try 
var selectVar = arrayVar.Select((a,i) => new { Line = a }); 

//or this (I find this syntax easier, but either works) 
var selectVar = 
    from s in arrayVar 
    select new { Line = s }; 

IEnumerable<'a> 실제로 : 그것이 색인 타입이 아니라면

4

당신은 VAR에 인덱스를 적용 할 수 없습니다. 그래도 쉽게 변환 할 수 있습니다.

//convert it to a List<'a> 
var aList = selectVar.ToList(); 

//convert it to a 'a[] 
var anArray = selectVar.ToArray(); 

//or even a Dictionary<string,'a> 
var aDictionary = selectVar.ToDictionary(x => x.Line); 
관련 문제