Come si indicizza in una var in LINQ?
Domanda
Sto cercando di far funzionare la seguente parte di codice in LINQPad ma non riesco a indicizzarla in una var.Qualcuno sa come indicizzare una var in 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>'
Soluzione
Come dice il commento, non è possibile applicare l'indicizzazione con []
a un'espressione di tipo System.Collections.Generic.IEnumerable<T>
.L'interfaccia IEnumerable supporta solo il metodo GetEnumerator()
.Tuttavia con LINQ puoi chiamare il metodo di estensione ElementAt(int)
.
Altri suggerimenti
Non puoi applicare un indice a una var a meno che non sia un tipo indicizzabile:
//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 };
In entrambi questi casi selectVar
è effettivamente IEnumerable<'a>
- non un tipo indicizzato.Puoi facilmente convertirlo in uno però:
//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 );
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow