IEnumerable和数组有什么区别? [英] What is the difference between IEnumerable and arrays?

查看:223
本文介绍了IEnumerable和数组有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都将描述IEnumerable,以及IEnumerable和数组之间的区别是什么 以及在哪里使用它..有关它的所有信息以及如何使用它.

Will anyone describe IEnumerable and what is difference between IEnumerable and array and where to use it.. all information about it and how to use it.

推荐答案

数组是具有指定大小的对象的集合.

An array is a collection of objects with a set size.

int[] array = [0, 1, 2];

这在您可能要访问集合中特定位置的项目的情况下非常有用,因为每个元素在内存中的位置是已知的

This makes it very useful in situations where you may want to access an item in a particular spot in the collection since the location in memory of each element is already known

array[1];

此外,可以快速计算数组的大小.

Also, the size of the array can be calculated quickly.

IEnumerable基本上说,给定开始位置,就有可能获得下一个值.一个例子可能是无数个数字:

IEnumerable, on the other hand, basically says that given a start position it is possible to get the next value. One example of this may be an infinite series of numbers:

public IEnumerable<int> Infinite()
{
    int i = 0;
    while(true)
        yield return i++;
}

与数组不同,可枚举的集合可以是任意大小,并且可以根据需要创建元素,而不是预先创建元素,这允许强大的构造,并且LINQ广泛使用它来促进复杂的查询.

Unlike an array an enumerable collection can be any size and it is possible to create the elements as they are required, rather than upfront, this allows for powerful constructs and is used extensively by LINQ to facilitate complex queries.

//This line won't do anything until you actually enumerate the created variable
IEnumerable<int> firstTenOddNumbers = Infinite().Where(x => x % 2 == 1).Take(10);

但是,获取特定元素的唯一方法是从头开始并枚举到所需元素.这比从预先生成的数组中获取元素要昂贵得多.

However the only way to get a specific element is to start at the beginning and enumerate through to the one you want. This will be considerably more expensive than getting the element from a pre-generated array.

您当然可以通过数组进行枚举,所以数组实现了IEnumerable接口.

Of course you can enumerate through an array, so an array implements the IEnumerable interface.

这篇关于IEnumerable和数组有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆