我们如何在LINQ中索引到var?

时间:2020-03-05 18:47:57  来源:igfitidea点击:

我正在尝试让以下代码在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>'

解决方案

回答

就像评论所说,不能将带有[]的索引应用于类型为System.Collections.Generic.IEnumerable <T>的表达式。 IEnumerable接口仅支持方法GetEnumerator()。但是,使用LINQ可以调用扩展方法ElementAt(int)

回答

我们不能将索引应用于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 &lt;'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 );