문제

내가 노력하고 다음과 같은 코드들에서 작동하 LINQPad 를 인덱스로 var.누구하는 방법을 알고 있으로 인덱스 var LINQ?

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>'
도움이 되었습니까?

해결책

주석으로 말한다 적용할 수 없습니다 인덱싱 [] 을 표현의 형식 System.Collections.Generic.IEnumerable<T>.니페이 인터페이스 만을 지원하는 방법 GetEnumerator().그러나 LINQ 호출할 수 있습니다 extension 방법 ElementAt(int).

다른 팁

적용할 수 없는 인덱스를 var 지 않는 한 그것은 인서 유형:

//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 };

이러한 두 경우 모두에서 selectVar 실제로 IEnumerable<'a> -하지 않는 인덱싱형입니다.당신은 쉽게 할 수 있으로 변환을 하지만:

//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 );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top