Pergunta

Estou tentando fazer com que o seguinte código funcione no LINQPad, mas não consigo indexar em uma var.Alguém sabe como indexar em um var no 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>'
Foi útil?

Solução

Como diz o comentário, você não pode aplicar a indexação com [] para uma expressão do tipo System.Collections.Generic.IEnumerable<T>.A interface IEnumerable suporta apenas o método GetEnumerator().Porém com LINQ você pode chamar o método de extensão ElementAt(int).

Outras dicas

Você não pode aplicar um índice a uma var, a menos que seja um tipo indexável:

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

Em ambos os casos selectVar é na verdade IEnumerable<'a> - não é um tipo indexado.Você pode facilmente convertê-lo em um:

//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 );
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top