如何在LINQ中索引变量?

时间:2008-09-04 23:48:18

标签: c# linq

我正在尝试使用以下一些代码在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>'

2 个答案:

答案 0 :(得分:21)

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

答案 1 :(得分: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 );