你也可以做到這一點,但它看起來像以前的職位是正確的爲好。
for(int i = 0; i < pizzas.Count; i++)
Console.WriteLine(pizzas.ElementAt(i));
Console.ReadLine();
編輯1:
如果不是很明顯,如果您想具體指標(1),將像這樣訪問:
string pizza = pizzas.ElementAt(1);
編輯2:
代碼錯誤。見編輯3.
編輯3:
考慮兩種方法,讓我們來測試它們。
代碼:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ElementAtOrIndex
{
class Program
{
// Declare/initialize static variables.
static Stopwatch timer = new Stopwatch();
static List<long> ElementAtTimes = new List<long>();
static List<long> IndexTimes = new List<long>();
static void Main(string[] args)
{
// Declare/initialize variables.
int count = 100000;
int iterations = 1000;
// Just initializes a list with elements from 0 to count.
// Slower than for loops, but pithy for an example on SO.
List<int> list = Enumerable.Range(0, count).ToList<int>();
// Assert that both methods are equal.
for (int i = 0; i < list.Count; i++)
{
if (list.ElementAt(i) != list[i])
{
Console.WriteLine("Both methods are not equal!");
Environment.Exit(1);
}
}
Console.WriteLine("Both methods are equal!");
// Time ElementAt access *iterations* times by copying into a variable.
for (int i = 0; i < iterations; i++)
{
// [Re]start the timer.
timer.Reset();
timer.Start();
int temp;
for (int j = 0; j < list.Count; j++)
temp = list.ElementAt(j);
// Note the time.
ElementAtTimes.Add(timer.ElapsedTicks);
}
// Time Index access *iterations* times by copying into a variable.
for (int i = 0; i < iterations; i++)
{
// [Re]start the timer.
timer.Reset();
timer.Start();
int temp;
for (int j = 0; j < list.Count; j++)
temp = list[j];
// Note the time.
IndexTimes.Add(timer.ElapsedTicks);
}
// Output times.
Console.WriteLine("Average time for ElementAt access: {0} ns", ElementAtTimes.Average()/count * 100);
Console.WriteLine("Average time for Index access: {0} ns", IndexTimes.Average()/count * 100);
Console.ReadLine();
}
}
}
測試:
http://goo.gl/Tf10R
輸出:
Both methods are equal!
Average time for ElementAt access: 25.101014 ns
Average time for Index access: 12.961065 ns
評論:
說到錯誤,MSDN文檔和大量經驗證據表明,這種擔憂是完全沒有根據的。如果列表發生變化,那麼這些更改當然會由兩種訪問方法反映出來。
索引訪問方法肯定是更快,但我想淡化多少。這是計時100,000次訪問。通過訪問進行訪問,速度只有幾納秒。這最終會加起來,但對於大多數應用程序來說是不必要的優化,並且這兩種方法最終都會做同樣的事情。另外,雖然這隻顯示訪問類型爲int的列表的時間,但我已經測試了具有類似結果的double,float和string類型的列表。如果需要,我可以發佈這些版本。
*索引訪問方法在所有情況下應該更快,但硬件上的里程差別很大。我的計算機對ElementAt()
和索引訪問方法的訪問時間分別爲5.71ns和0.27ns。
它就像一個數組然後ty – Ryan 2012-04-21 01:17:43
@Eron它們有很多共同之處 – nawfal 2012-04-21 01:18:08