I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a 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>'
As the comment says, you cannot apply indexing with []
to an expression of type System.Collections.Generic.IEnumerable<T>
. The IEnumerable interface only supports the method GetEnumerator()
. However with LINQ you can call the extension method ElementAt(int)
.
You can't apply an index to a var unless it's an indexable 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 };
In both these cases selectVar
is actually IEnumerable<'a>
- not an indexed type. You can easily convert it to one though:
//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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With