Comment avez-vous index dans une var dans LINQ?
Question
Je vais essayer d'obtenir les bits suivants du code de travail dans LINQPad, mais je suis incapable d'index dans une var.Quelqu'un sait comment l'index dans une 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>'
La solution
Comme le commentaire dit, vous ne pouvez pas appliquer l'indexation avec []
pour 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)
.
Autres conseils
Vous ne pouvez pas appliquer un indice du var, à moins que c'est une fraise de type:
//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>
- non indexé type.Vous pouvez facilement convertir un bien:
//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 );
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow