如何在不使用foreach循环的情况下从列表中检索元素?
答案 0 :(得分:6)
var list = new List<int> { 1, 2, 3, 4, 5 };
for (int i = 0; i < list.Count(); i++)
{
var element = list[i];
}
或
var list = new List<int> { 1, 2, 3, 4, 5 };
using (var enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
var element = enumerator.Current;
}
}
答案 1 :(得分:1)
你说列表,但你没有将List<T>
类指定为this answer assumes(同样,可能会添加该答案使用Count()扩展方法。因为你知道类型是List<T>
最好使用Count 属性)。
如果您始终使用IList<T>
接口实现,那么使用迭代索引的for循环然后使用该值访问索引器将正常工作。
但是,如果您正在处理IEnumerable<T>
实施,那么这并不总是有效。相反,您必须执行以下操作:
// Get the IEnumerator<T> from the list.
IEnumerator<T> enumerator = list.GetEnumerable();
// Dispose if necessary.
using (enumerator as IDisposable)
{
// Cycle while there are items.
while (enumerator.MoveNext())
{
// Work with enumerator.Current here.
}
}
这是编译器在编译时扩展foreach语句的方式。基本上,由于IEnumerable<T>
实现可以实现IDisposable,它通过尝试强制转换为IDisposable来为这种可能性做好准备。如果不能,则using语句在退出时不会执行任何操作。
在数组上使用foreach时,编译器将扩展为一个循环,通过索引访问项目(假设您直接使用数组实例),而不是上面的枚举器方法。
答案 2 :(得分:1)
如果你想避免这种类型的循环:
foreach(var item in list) {};
...然后您可以使用Linq或Lambda表达式从列表中搜索和检索。
例如:
using System.Linq;
// ... with Lambda
var ints = new List<int>(){1,2,3,4,5};
var evenInts = ints.ForEach(i => i % 2 == 0);
// with straight Linq-to-objects:
var oddInts = from i in ints
where i % 2 == 1
select i;