foreach 循环内的 foreach:
var list1 = new List<int>() {0,1,2,3,4,5,6,7,8,9};
var list2 = new List<int>() {9,8,7,6,5,4,3,2,1,0};
foreach (var list1Value in list1)
{
foreach (var list2Value in list2)
{
if (list1Value == list2Value)
// do something
}
}
或 foreach 循环内的 IEnumerable
var list1 = new List<int>() {0,1,2,3,4,5,6,7,8,9};
var list2 = new List<int>() {9,8,7,6,5,4,3,2,1,0}
var enumerator = (System.Collections.IEnumerator)list2.GetEnumerator();
foreach (var list1Value in list1)
{
enumerator.Reset();
while (enumerator.MoveNext())
{
if (list1Value == (int)enumerator.Current)
// Do something
}
}
我更喜欢第一个可读性,但认为第二个更有效。请注意,代码只是一个示例,并不代表我实际运行的代码。