我首先运行了以下代码:
var stringList = new[]{"A","BB","CCC","DDDD"};
var dictionary = new Dictionary<int, string>();
var stopwatch = new Stopwatch();
stopwatch.Start();
foreach (var s in stringList)
{
dictionary.Add(s.Length,s);
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.ReadKey();
执行时间为:00:00:00.0000205
然后我运行了以下代码...
var stringList = new[]{"A","BB","CCC","DDDD"};
var stopwatch = new Stopwatch();
stopwatch.Start();
var dictionary = stringList.ToDictionary(s => s.Length);
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.ReadKey();
执行时间为:00:00:00.0037431
这是否证明 foreach 比 LINQ 更好?