2008-09-04 6 views
10

J'essaie d'obtenir le bit de code suivant pour travailler dans LINQPad mais je suis incapable d'indexer dans un var. Quelqu'un sait comment indexer dans un var dans LINQ?Comment indexez-vous un var dans 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>' 

Répondre

21

Comme le commentaire dit, vous ne pouvez pas appliquer l'indexation avec [] à une expression de type System.Collections.Generic.IEnumerable<T>. L'interface IEnumerable prend uniquement en charge la méthode GetEnumerator(). Cependant, avec LINQ, vous pouvez appeler la méthode d'extension ElementAt(int).

4

Vous ne pouvez pas appliquer un index à un var moins que ce soit un type indexable:

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

Dans ces deux cas selectVar est en fait IEnumerable<'a> - pas un type indexé. Vous pouvez facilement le convertir en un si:

//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); 
Questions connexes