除非它是可索引类型,否则不能将索引应用于 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 );