10

我试图让以下代码在 LINQPad 中工作,但无法索引到 var。有人知道如何在 LINQ 中索引 var 吗?

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>'
4

2 回答 2

21

正如评论所说,您不能将索引应用于[]type 的表达式System.Collections.Generic.IEnumerable<T>。IEnumerable 接口只支持方法GetEnumerator()。但是使用 LINQ,您可以调用扩展方法ElementAt(int)

于 2008-09-04T23:51:26.003 回答
4

除非它是可索引类型,否则不能将索引应用于 var:

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

在这两种情况下selectVar实际上是IEnumerable<'a>- 不是索引类型。您可以轻松地将其转换为一个:

//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 );
于 2008-09-05T14:39:14.040 回答