tags:

views:

901

answers:

2

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>'
+7  A: 

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).

Joseph Daigle
+1  A: 

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 );
Keith