[英]How to retrieve the elements in list without using foreach loop in C#?
如何在不使用foreach循环的情况下从列表中检索元素?
var list = new List<int> { 1, 2, 3, 4, 5 };
for (int i = 0; i < list.Count(); i++)
{
var element = list[i];
}
or 要么
var list = new List<int> { 1, 2, 3, 4, 5 };
using (var enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
var element = enumerator.Current;
}
}
You say list, but you don't specify the List<T>
class as this answer assumes (also, it might be added that that answer uses the Count() extension method. Since you know the type is of List<T>
it's better to use the Count property ). 您说的是list,但未按此答案的假设指定List<T>
类(同样,可能还会添加该答案使用Count()扩展方法。由于您知道类型为List<T>
因此它是最好使用Count 属性 )。
If you are always working with the IList<T>
interface implementation, then using a for loop that iterates an index and then accesses the indexer with that value will work fine. 如果您始终使用IList<T>
接口实现,则使用for循环迭代索引,然后使用该值访问索引器将可以正常工作。
However, if you are dealing with IEnumerable<T>
implementations, that will not always work. 但是,如果您正在处理IEnumerable<T>
实现,则该方法将永远无法正常工作。 Rather, you have to do the following: 而是,您必须执行以下操作:
// 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.
}
}
This is how the compiler expands the foreach statement when it is compiled. 这就是编译器在编译时扩展foreach语句的方式。 Basically, since IEnumerable<T>
implementations can implement IDisposable, it prepares for that eventuality by trying to cast to IDisposable. 基本上,由于IEnumerable<T>
实现可以实现IDisposable,因此它通过尝试转换为IDisposable来为可能的情况做准备。 If it cannot, then the using statement just doesn't do anything on exit. 如果不能,则using语句在退出时不执行任何操作。
When using foreach on arrays, the compiler will expand to a loop which accesses the items by index (assuming you are working with an array instance directly), not the enumerator approach above. 在数组上使用foreach时,编译器将扩展到一个循环,该循环通过索引(假设您直接使用数组实例)来访问项,而不是上面的枚举器方法。
If you're trying to avoid this type of loop: 如果您试图避免这种类型的循环:
foreach(var item in list) {};
...then you can use Linq or Lambda expressions to search and retrieve from the list. ...然后您可以使用Linq或Lambda表达式从列表中搜索和检索。
For example: 例如:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.