Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you index into a var in LINQ?

Tags:

c#

linq

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>'
like image 670
Guy Avatar asked Sep 04 '08 23:09

Guy


2 Answers

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

like image 64
Joseph Daigle Avatar answered Oct 28 '22 19:10

Joseph Daigle


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 );
like image 4
Keith Avatar answered Oct 28 '22 19:10

Keith