### 迭代强类型泛型List <t>的最佳方法是什么？</t>

#### 7 个答案:

``````foreach(ObjectType objectItem in objectTypeList)
{
// ...do some stuff
}
``````

Purple Ant

``````For Each objectItem as ObjectType in objectTypeList
'Do some stuff '
Next
``````

``````//C#
foreach( var item in listVariable) {
//do stuff
}
``````

``````//C#
int[] valueTypeArray;
for(int i=0; i < valueTypeArray.Length; ++i) {
int item = valueTypeArray[i];
//do stuff
}
``````

<强>更新

``````// create a list to test with
var theList = Enumerable.Range(0, 100000000).ToList();

// time foreach
var sw = Stopwatch.StartNew();
foreach (var item in theList)
{
int inLoop = item;
}
Console.WriteLine("list  foreach: " + sw.Elapsed.ToString());

sw.Reset();
sw.Start();

// time for
int cnt = theList.Count;
for (int i = 0; i < cnt; i++)
{
int inLoop = theList[i];
}
Console.WriteLine("list  for    : " + sw.Elapsed.ToString());

// now run the same tests, but with an array
var theArray = theList.ToArray();

sw.Reset();
sw.Start();

foreach (var item in theArray)
{
int inLoop = item;
}
Console.WriteLine("array foreach: " + sw.Elapsed.ToString());

sw.Reset();
sw.Start();

// time for
cnt = theArray.Length;
for (int i = 0; i < cnt; i++)
{
int inLoop = theArray[i];
}
Console.WriteLine("array for    : " + sw.Elapsed.ToString());

``````

``````list  foreach: 00:00:00.5137506
list  for    : 00:00:00.2417709
array foreach: 00:00:00.1085653
array for    : 00:00:00.0954890
``````

``````list  foreach: 00:00:01.1289015
list  for    : 00:00:00.9945345
array foreach: 00:00:00.6405422
array for    : 00:00:00.4913245
``````

``````For Each tmpObject as ObjectType in ObjectTypeList
'Do some stuff '
Next``````

C＃

``````myList<string>().ForEach(
delegate(string name)
{
Console.WriteLine(name);
});
``````

C＃

``````myList<string>().ForEach(name => Console.WriteLine(name));
``````

VB.Net

``````myList(Of String)().ForEach(Function(name) Console.WriteLine(name))
``````

``````public IEnumerable<String> Paths(Func<String> formatter) {
List<String> paths = new List<String>()
{
};

return paths.ForEach(formatter);
}
``````

``````var hostname = "myhost.com";
var formatter = f => String.Format("http://{0}{1}", hostname, f);
IEnumerable<String> absolutePaths = Paths(formatter);
``````

• for循环，如果效率是优先考虑的话
• foreach循环或ForEach方法，无论哪个更清楚地传达您的意图

``````for(int i = 0; i < genericList.Count; ++i)
{
// Loop body
}
``````

``````foreach(<insertTypeHere> o in genericList)
{
// Loop body
}
``````