列表和IEnumerable之间的实际差异 [英] Practical difference between List and IEnumerable

查看:170
本文介绍了列表和IEnumerable之间的实际差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过阅读类似的帖子我已经了解到,列表是一种IEnumerable的的。但我真的不知道这两者之间的实际差别实际上是什么。

By reading similar posts I've learned that a List is a type of IEnumerable. But I'm really wondering what the practical difference between those two actually is.

要有人谁总是已经使用了列表和从未使用过的IEnumerable

To someone who always have used a List and never used IEnumerable:

  • 什么是两者之间的实际区别?
  • 在什么情况下是他们中的一个比另一个好?

下面是一个实例: 我们要存储四根弦,责令其按字母顺序,将它们传递到另一个函数,然后显示给用户的结果。什么我们用,为什么?

Here is a practical example: We want to store four strings, order them alphabetically, pass them to another function and then show the user the result. What would we use and why?

希望有人可以排序了这一点,我或点我在正确的方向。 在此先感谢!

Hopefully someone can sort this out for me or point me in the right direction. Thanks in advance!

推荐答案

IEnumerable和列表之间的一个重要区别(除了一个是一个接口和另一个是一个具体的类)是IEnumerable的只读和List不是。

One important difference between IEnumerable and List (besides one being an interface and the other being a concrete class) is that IEnumerable is read-only and List is not.

因此​​,如果您需要任何形式的永久更改到您的收藏(添加和放大器;删除)的能力,你需要列出。如果你只需要阅读,排序和/或过滤您的收藏,IEnumerable的是足够用于这一目的。

So if you need the ability to make permanent changes of any kind to your collection (add & remove), you'll need List. If you just need to read, sort and/or filter your collection, IEnumerable is sufficient for that purpose.

因此​​,在你实际的例子,如果你想添加的四根弦一次,你需要列出。但是,如果你被实例化您的收藏全部一次,你可以使用的IEnumerable

So in your practical example, if you wanted to add the four strings one at a time, you'd need List. But if you were instantiating your collection all at once, you could use IEnumerable.

IEnumerable firstFourLettersOfAlphabet = new[]{"a","b","c","d"};

您可以再使用LINQ过滤或列表进行排序,但是你想要的。

You could then use LINQ to filter or sort the list however you wanted.

这篇关于列表和IEnumerable之间的实际差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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