列表(T)和集合(T)有什么区别?

时间:2021-11-25 13:27:46

I've seen them used in a lot of the same ways, and I am worried I'm about to go down a path in design that is irreversible if I don't understand this better. Also, I am using .NET.

我见过它们以许多相同的方式使用,我担心如果我不能更好地理解这一点,我将走上设计的不可逆之路。另外,我正在使用。net。

12 个解决方案

#1


44  

Collection<T> is a customizable wrapper around IList<T>. While IList<T> is not sealed, it doesn't provide any customization points. Collection<T>'s methods are by default delegated to the standard IList<T> methods, but can be easily overridden to do what you want. It is also possible to wireup events inside a Collection<T> that I don't believe could be done with an IList.

集合 是一个可定制的包装器,围绕IList 。虽然IList 不是密封的,但它不提供任何定制点。集合 的方法默认地被委托给标准的IList 方法,但是可以很容易地重写以执行您想要的操作。也有可能在集合 中窃听事件,我认为用IList无法做到这一点。

In short, it's much easier to extend it after the fact, which could potentially mean a lot less refactoring.

简而言之,在事实之后扩展它要容易得多,这可能意味着更少的重构。

#2


47  

In C#, there are three concepts for representing a bag of objects. In order of increasing features, they are:

在c#中,有三个代表一袋对象的概念。为了增加特征,它们是:

  • Enumerable - unordered, unmodifiable
  • 可列举的,无序的,无法改变的
  • Collection - can add/remove items
  • 收集-可以添加/删除项目
  • List - allows items to have an order (accessing and removing by index)
  • 列表——允许项目有一个顺序(通过索引访问和删除)

Enumerable has no order. You cannot add or remove items from the set. You cannot even get a count of items in the set. It strictly lets you access each item in the set, one after the other.

可列举的没有秩序。不能添加或删除集合中的项,甚至不能获得集合中的项数,它严格地允许您逐个访问集合中的每个项。

Collection is a modifiable set. You can add and remove objects from the set, you can also get the count of items in the set. But there still is no order, and because there is no order: no way to access an item by index, nor is there any way to sort.

集合是一组修改。您可以添加和删除对象的设置,你也可以计数的物品。但是还没有订单,因为没有秩序,没有办法通过索引访问一个项目,也没有任何办法。

List is an ordered set of objects. You can sort the list, access items by index, remove items by index.

List是一组有序的对象。您可以对列表进行排序,按索引访问项目,按索引删除项目。

In fact, when looking at the interfaces for these, they build on one another:

事实上,当我们看这些接口时,它们是建立在彼此的基础之上的:

  • interface IEnumerable<T>

    IEnumerable接口< T >

    • GetEnumeration<T>
    • GetEnumeration < T >
  • interface ICollection<T> : IEnumerable<T>

    接口ICollection < T >:IEnumerable < T >

    • Add
    • 添加
    • Remove
    • 删除
    • Clear
    • 清晰的
    • Count
  • interface IList<T> = ICollection<T>

    接口IList < T > = ICollection < T >

    • Insert
    • 插入
    • IndexOf
    • IndexOf
    • RemoveAt
    • RemoveAt

When declaring variables, or method parameters, you should choose to use

在声明变量或方法参数时,应该选择使用

  • IEnumerable
  • IEnumerable
  • ICollection
  • ICollection
  • IList
  • IList

based on conceptually you need to do with the set of objects.

根据概念,您需要处理对象集。

If you just need to be able to do something to every object in a list, then you only need IEnumerable:

如果你只需要对列表中的每个对象做一些事情,那么你只需要IEnumerable:

void SaveEveryUser(IEnumerable<User> users)
{
    for User u in users
      ...
}

You don't care if the Users are kept in a List<T>, Collection<T>, Array<T> or anything else. You only need the IEnumerable<T> interface.

您不关心用户是否保存在列表 、集合 、数组 或其他内容中。只需IEnumerable 接口。

If you need to be able to add, remove, or count the items in a set, then use a Collection:

如果您需要能够添加、删除或计数集合中的项目,则使用集合:

ICollection<User> users = new Collection<User>();
users.Add(new User());

If you care about a sort order, and need the order to be correct, then use a List:

如果您关心排序顺序,并且需要正确的顺序,那么请使用列表:

IList<User> users = FetchUsers(db);

In chart form:

以图表形式:

| Feature                | IEnumerable<T> | ICollection<T> | IList<T> |
|------------------------|----------------|----------------|----------|
| Enumerating items      | X              | X              | X        |
|                        |                |                |          |
| Adding items           |                | X              | X        |
| Removing items         |                | X              | X        |
| Count of items         |                | X              | X        |
|                        |                |                |          |
| Accessing by index     |                |                | X        |
| Removing by indexx     |                |                | X        |
| Getting index of item  |                |                | X        |

The List<T> and Collection<T> in System.Collections.Generic are two classes that implement these interfaces; but they aren't the only classes:

在System.Collections中列表 和Collection 。泛型是实现这些接口的两个类;但它们不是唯一的课程:

  • ConcurrentBag<T> is an ordered bag of objects (IEnumerable<T>)
  • ConcurrentBag 是一个有序的对象包(IEnumerable )
  • LinkedList<T> is a bag where you are not allowed to access items by index (ICollection); but you can arbitrarily add and remove items from the collection
  • LinkedList 是一个不允许按索引(ICollection)访问物品的包;但是您可以任意添加和删除集合中的项
  • SynchronizedCollection<T> in an ordered collection, where you can add/remove items by index
  • 同步集合 在有序集合中,您可以通过索引添加/删除项。

So you can easily change:

所以你可以很容易地改变:

IEnumerable<User> users = new SynchronizedCollection<User>();

SaveEveryUser(users);

tl;dr

  • Enumerable - access items, unordered, unmodifiable
  • 可列举-访问项目,无序,不可修改
  • Collection - can be modified (add,delete,count)
  • 集合——可以修改(添加、删除、计数)
  • List - can access by index
  • 列表-可以通过索引访问

Choose the concept you need, then use the matching class.

选择所需的概念,然后使用匹配类。

#3


42  

List<T> is intended for internal use within the application code. You should avoid writing public APIs that accept or return List<T> (consider using a superclass or a collection interface instead).

列表 是用于应用程序代码内部使用的。您应该避免编写接受或返回List< t>的公共api(考虑使用超类或集合接口)。

Collection<T> serves a base class for custom collections (although it can be used directly).

集合 为自定义集合提供基类(尽管它可以直接使用)。

Consider using Collection<T> in your code unless there are specific features of List<T> that you need.

考虑在代码中使用Collection ,除非您需要List 的特定特性。

The above are just recommendations.

以上只是一些建议。

[Adapted from: Framework Design Guidelines, Second Edition]

[改编自:框架设计指南,第二版]

#4


35  

List<T> is a very commonly seen container, because it is so very versatile (with lots of handy methods like Sort, Find, etc) - but has no extension points if you want to override any of the behaviour (check items on insert, for example).

List 是一个非常常见的容器,因为它是非常通用的(具有许多方便的方法,如Sort、Find等)——但是如果您想重写任何行为(例如,在insert上检查项目),则没有扩展点。

Collection<T> is a wrapper around any IList<T> (defaulting to List<T>) - it has the extension points (virtual methods), but not as many support methods like Find. Because of the indirection, it is slightly slower than List<T>, but not by much.

集合 是任何IList (默认为List )的包装器——它有扩展点(虚拟方法),但没有像Find这样的支持方法那么多。由于是间接的,它比List 稍微慢一点,但不是很多。

With LINQ, the extra methods in List<T> become less important, since LINQ-to-Objects tends to provide them anyway... for example First(pred), OrderBy(...), etc.

有了LINQ, List 中的额外方法就变得不那么重要了,因为LINQ-to- object无论如何都会提供它们……例如First(pred)、OrderBy(…)等等。

#5


12  

List is faster.

列表是更快。

Do for example

做的例如

private void button1_Click(object sender, EventArgs e)
{
  Collection<long> c = new Collection<long>();
  Stopwatch s = new Stopwatch();
  s.Start();
  for (long i = 0; i <= 10000000; i++)
  {
    c.Add(i);
  }
  s.Stop();
  MessageBox.Show("collect " + s.ElapsedMilliseconds.ToString());

  List<long> l = new List<long>();
  Stopwatch s2 = new Stopwatch();
  s2.Start();
  for (long i = 0; i <= 10000000; i++)
  {
    l.Add(i);
  }
  s2.Stop();
  MessageBox.Show("lis " + s2.ElapsedMilliseconds.ToString());


}

on my machine List<> is almost twice as fast.

在我的机器列表中,<>几乎是两倍的速度。

Edit

编辑

I can't understand why people are downvoting this. Both on my work machine and my home machine the List<> code is 80% faster.

我不明白为什么人们会反对这样做。在我的工作机器和我的家庭机器上,列表<>代码快了80%。

#6


11  

List represents a collection where the order of items is important. It also supports methods s.a. Sort and search. Collection is a more general data-structure which makes less assumptions about the data and also supports less methods to manipulate it. If you want to expose a custom data structure, you should probably extend the collection. If you need to manipulate data w/o exposing the data-structure, a list is probably the more convenient way to go.

List表示项顺序很重要的集合。它还支持方法s.a. Sort和search。集合是一种更通用的数据结构,它对数据的假设更少,并且支持更少的方法来操作它。如果您想要公开自定义数据结构,那么应该扩展集合。如果您需要操作公开数据结构的数据w/o,那么列表可能是更方便的方法。

#7


4  

This is one of those grad school questions. A Collection of T is sort of abstract; there may be a default implementation (I'm not a .net/c# guy) but a collection will have basic operations like add, remove, iterate, and so on.

这是研究生院的问题之一。T的集合有点抽象;可能有一个默认实现(我不是.net/c#人员),但是集合将具有基本操作,如添加、删除、迭代等等。

List of T implies some specifics about these operations: add should take constant time, remove should take time proportional to the number of elements, getfirst should be consant time. In general, a List is a kind of Collection, but a Collection isn't necessarily a kind of List.

T列表暗示了一些关于这些操作的细节:添加应该花费常数时间,删除应该花费与元素数量成比例的时间,getfirst应该是consant time。一般来说,列表是一种集合,但是集合不一定是一种列表。

#8


4  

Hanselman Speaks: "Collection<T> looks like a list, and it even has a List<T> internally. EVERY single method delegates to the internal List<T>. It includes a protected property that exposes the List<T>."

Hanselman说:“Collection 看起来像一个list,甚至内部还有一个list 。每个方法都委托给内部列表 。它包含一个受保护的属性,该属性公开列表

EDIT: Collection<T> doesn't exist in System.Generic.Collections .NET 3.5. If you migrate from .NET 2.0 to 3.5 you'll need to change some code if you're using a lot of Collection<T> objects, unless I'm missing something obvious...

编辑:集合 在System.Generic中不存在。集合。net 3.5。如果您从。net 2.0迁移到3.5,那么如果您正在使用大量的集合 对象,那么您将需要修改一些代码,除非我遗漏了一些明显的东西……

EDIT 2: Collection<T> is now in the System.Collections.ObjectModel namespace in .NET 3.5. The help file says this:

编辑2:Collection 现在在System.Collections中。. net 3.5中的ObjectModel名称空间。帮助文件是这样写的:

"The System.Collections.ObjectModel namespace contains classes that can be used as collections in the object model of a reusable library. Use these classes when properties or methods return collections."

“System.Collections。ObjectModel名称空间包含可以作为可重用库的对象模型中的集合使用的类。当属性或方法返回集合时使用这些类。

#9


4  

All of these interfaces inherit from IEnumerable, which you should make sure you understand. That interface basically lets you use the class in a foreach statement (in C#).

所有这些接口都继承自IEnumerable,您应该确保理解它。该接口基本上允许您在foreach语句(在c#中)中使用该类。

  • ICollection is the most basic of the interfaces you listed. It's an enumerable interface that supports a Count and that's about it.
  • ICollection是您列出的最基本的接口。它是一个可枚举的接口,支持计数,仅此而已。
  • IList is everything that ICollection is, but it also supports adding and removing items, retrieving items by index, etc. It's the most commonly-used interface for "lists of objects", which is vague I know.
  • IList是ICollection的全部,但它也支持添加和删除项、按索引检索项等。它是“对象列表”最常用的接口,我知道这是模糊的。
  • IQueryable is an enumerable interface that supports LINQ. You can always create an IQueryable from an IList and use LINQ to Objects, but you also find IQueryable used for deferred execution of SQL statements in LINQ to SQL and LINQ to Entities.
  • IQueryable是一个支持LINQ的可枚举接口。您总是可以从IList创建一个IQueryable,并使用LINQ到对象,但是您也可以发现IQueryable用于延迟执行LINQ到SQL的SQL语句,以及将LINQ到实体的SQL语句。
  • IDictionary is a different animal in the sense that it is a mapping of unique keys to values. It is also enumerable in that you can enumerate the key/value pairs, but otherwise it serves a different purpose than the others you listed
  • IDictionary是另一种动物,因为它是唯一键到值的映射。它也是可枚举的,因为您可以枚举键/值对,但否则它的用途与您列出的其他用途不同

#10


4  

According to MSDN, List(Of T).Add is "an O(n) operation" (when "Capacity" is exceeded) while Collection(Of T).Add is always "an O(1) operation". That would understandable if List is implemented using an Array and Collection a Linked List. However, if that were the case, one would expect Collection(Of T).Item to be "an O(n) operation". But - it's - not!?! Collection(Of T).Item is "an O(1) operation" just like List(Of T).Item.

根据MSDN, List(Of T). add是“O(n)操作”(当“容量”被超过),而集合(T). add总是“O(1)操作”。如果使用数组实现List并使用链表集合,则可以理解。但是,如果是这种情况,则可以期望集合(T). item为“O(n)操作”。但是-不是-不是!集合(T). item是O(1)操作,就像列表(T). item。

On top of that, "tuinstoel"'s "Dec 29 '08 at 22:31" post above claims speed tests show List(Of T).Add to be faster than Collection(Of T).Add which I've reproduced with Long's and String's. Although I only got ~33% faster vs. his claimed 80%, according MSDN, it should've been the opposite and by "n" times!?!

除此之外,“tuinstoel”’s“Dec 29’08 at 22:31”发布了以上索赔速度测试清单(T)。增加比收集(T)要快。虽然我只比他声称的80%快了33%,但是根据MSDN的说法,应该是相反的,应该是n次!

#11


3  

Both implement the same interfaces, so they'll behave the same way. Perhaps they are implemented differently internally, but this would have to be tested.

两者实现相同的接口,因此它们的行为方式相同。也许它们在内部执行的方式不同,但这必须经过测试。

The only real differences I see are the namespaces and the fact that Collection<T> is marked with ComVisibleAttribute(false), so COM code can't use it.

我看到的唯一真正的区别是名称空间和集合 被用ComVisibleAttribute(false)标记的事实,所以COM代码不能使用它。

#12


3  

In addition to other asnwers, I've compiled quick overview of generic list and collection capabilities. Collection is limited subset of the List:

除了其他asnwers之外,我还简要概述了通用列表和集合功能。集合是列表的有限子集:

* = present
o = partially present

Property/Method   Collection<T>   List<T>
----------------------------------------------
Add()                *              *
AddRange()                          *
AsReadOnly()                        *
BinarySearch()                      *
Capacity                            *
Clear()              *              *
Contains()           *              *
ConvertAll()                        *
CopyTo()             o              *
Count                *              *
Equals()             *              *
Exists()                            *
Find()                              *
FindAll()                           *
FindIndex()                         *
FindLast()                          *
FindLastIndex()                     *
ForEach()                           *
GetEnumerator()      *              *
GetHashCode()        *              *
GetRange()                          *
GetType()            *              *
IndexOf()            o              *
Insert()             *              *
InsertRange()                       *
Item()               *              *
LastIndexOf()                       *
New()                o              *
ReferenceEquals()    *              *
Remove()             *              *
RemoveAll()                         *
RemoveAt()           *              *
RemoveRange()                       *
Reverse()                           *
Sort()                              *
ToArray()                           *
ToString()           *              *
TrimExcess()                        *
TrueForAll()                        *

#1


44  

Collection<T> is a customizable wrapper around IList<T>. While IList<T> is not sealed, it doesn't provide any customization points. Collection<T>'s methods are by default delegated to the standard IList<T> methods, but can be easily overridden to do what you want. It is also possible to wireup events inside a Collection<T> that I don't believe could be done with an IList.

集合 是一个可定制的包装器,围绕IList 。虽然IList 不是密封的,但它不提供任何定制点。集合 的方法默认地被委托给标准的IList 方法,但是可以很容易地重写以执行您想要的操作。也有可能在集合 中窃听事件,我认为用IList无法做到这一点。

In short, it's much easier to extend it after the fact, which could potentially mean a lot less refactoring.

简而言之,在事实之后扩展它要容易得多,这可能意味着更少的重构。

#2


47  

In C#, there are three concepts for representing a bag of objects. In order of increasing features, they are:

在c#中,有三个代表一袋对象的概念。为了增加特征,它们是:

  • Enumerable - unordered, unmodifiable
  • 可列举的,无序的,无法改变的
  • Collection - can add/remove items
  • 收集-可以添加/删除项目
  • List - allows items to have an order (accessing and removing by index)
  • 列表——允许项目有一个顺序(通过索引访问和删除)

Enumerable has no order. You cannot add or remove items from the set. You cannot even get a count of items in the set. It strictly lets you access each item in the set, one after the other.

可列举的没有秩序。不能添加或删除集合中的项,甚至不能获得集合中的项数,它严格地允许您逐个访问集合中的每个项。

Collection is a modifiable set. You can add and remove objects from the set, you can also get the count of items in the set. But there still is no order, and because there is no order: no way to access an item by index, nor is there any way to sort.

集合是一组修改。您可以添加和删除对象的设置,你也可以计数的物品。但是还没有订单,因为没有秩序,没有办法通过索引访问一个项目,也没有任何办法。

List is an ordered set of objects. You can sort the list, access items by index, remove items by index.

List是一组有序的对象。您可以对列表进行排序,按索引访问项目,按索引删除项目。

In fact, when looking at the interfaces for these, they build on one another:

事实上,当我们看这些接口时,它们是建立在彼此的基础之上的:

  • interface IEnumerable<T>

    IEnumerable接口< T >

    • GetEnumeration<T>
    • GetEnumeration < T >
  • interface ICollection<T> : IEnumerable<T>

    接口ICollection < T >:IEnumerable < T >

    • Add
    • 添加
    • Remove
    • 删除
    • Clear
    • 清晰的
    • Count
  • interface IList<T> = ICollection<T>

    接口IList < T > = ICollection < T >

    • Insert
    • 插入
    • IndexOf
    • IndexOf
    • RemoveAt
    • RemoveAt

When declaring variables, or method parameters, you should choose to use

在声明变量或方法参数时,应该选择使用

  • IEnumerable
  • IEnumerable
  • ICollection
  • ICollection
  • IList
  • IList

based on conceptually you need to do with the set of objects.

根据概念,您需要处理对象集。

If you just need to be able to do something to every object in a list, then you only need IEnumerable:

如果你只需要对列表中的每个对象做一些事情,那么你只需要IEnumerable:

void SaveEveryUser(IEnumerable<User> users)
{
    for User u in users
      ...
}

You don't care if the Users are kept in a List<T>, Collection<T>, Array<T> or anything else. You only need the IEnumerable<T> interface.

您不关心用户是否保存在列表 、集合 、数组 或其他内容中。只需IEnumerable 接口。

If you need to be able to add, remove, or count the items in a set, then use a Collection:

如果您需要能够添加、删除或计数集合中的项目,则使用集合:

ICollection<User> users = new Collection<User>();
users.Add(new User());

If you care about a sort order, and need the order to be correct, then use a List:

如果您关心排序顺序,并且需要正确的顺序,那么请使用列表:

IList<User> users = FetchUsers(db);

In chart form:

以图表形式:

| Feature                | IEnumerable<T> | ICollection<T> | IList<T> |
|------------------------|----------------|----------------|----------|
| Enumerating items      | X              | X              | X        |
|                        |                |                |          |
| Adding items           |                | X              | X        |
| Removing items         |                | X              | X        |
| Count of items         |                | X              | X        |
|                        |                |                |          |
| Accessing by index     |                |                | X        |
| Removing by indexx     |                |                | X        |
| Getting index of item  |                |                | X        |

The List<T> and Collection<T> in System.Collections.Generic are two classes that implement these interfaces; but they aren't the only classes:

在System.Collections中列表 和Collection 。泛型是实现这些接口的两个类;但它们不是唯一的课程:

  • ConcurrentBag<T> is an ordered bag of objects (IEnumerable<T>)
  • ConcurrentBag 是一个有序的对象包(IEnumerable )
  • LinkedList<T> is a bag where you are not allowed to access items by index (ICollection); but you can arbitrarily add and remove items from the collection
  • LinkedList 是一个不允许按索引(ICollection)访问物品的包;但是您可以任意添加和删除集合中的项
  • SynchronizedCollection<T> in an ordered collection, where you can add/remove items by index
  • 同步集合 在有序集合中,您可以通过索引添加/删除项。

So you can easily change:

所以你可以很容易地改变:

IEnumerable<User> users = new SynchronizedCollection<User>();

SaveEveryUser(users);

tl;dr

  • Enumerable - access items, unordered, unmodifiable
  • 可列举-访问项目,无序,不可修改
  • Collection - can be modified (add,delete,count)
  • 集合——可以修改(添加、删除、计数)
  • List - can access by index
  • 列表-可以通过索引访问

Choose the concept you need, then use the matching class.

选择所需的概念,然后使用匹配类。

#3


42  

List<T> is intended for internal use within the application code. You should avoid writing public APIs that accept or return List<T> (consider using a superclass or a collection interface instead).

列表 是用于应用程序代码内部使用的。您应该避免编写接受或返回List< t>的公共api(考虑使用超类或集合接口)。

Collection<T> serves a base class for custom collections (although it can be used directly).

集合 为自定义集合提供基类(尽管它可以直接使用)。

Consider using Collection<T> in your code unless there are specific features of List<T> that you need.

考虑在代码中使用Collection ,除非您需要List 的特定特性。

The above are just recommendations.

以上只是一些建议。

[Adapted from: Framework Design Guidelines, Second Edition]

[改编自:框架设计指南,第二版]

#4


35  

List<T> is a very commonly seen container, because it is so very versatile (with lots of handy methods like Sort, Find, etc) - but has no extension points if you want to override any of the behaviour (check items on insert, for example).

List 是一个非常常见的容器,因为它是非常通用的(具有许多方便的方法,如Sort、Find等)——但是如果您想重写任何行为(例如,在insert上检查项目),则没有扩展点。

Collection<T> is a wrapper around any IList<T> (defaulting to List<T>) - it has the extension points (virtual methods), but not as many support methods like Find. Because of the indirection, it is slightly slower than List<T>, but not by much.

集合 是任何IList (默认为List )的包装器——它有扩展点(虚拟方法),但没有像Find这样的支持方法那么多。由于是间接的,它比List 稍微慢一点,但不是很多。

With LINQ, the extra methods in List<T> become less important, since LINQ-to-Objects tends to provide them anyway... for example First(pred), OrderBy(...), etc.

有了LINQ, List 中的额外方法就变得不那么重要了,因为LINQ-to- object无论如何都会提供它们……例如First(pred)、OrderBy(…)等等。

#5


12  

List is faster.

列表是更快。

Do for example

做的例如

private void button1_Click(object sender, EventArgs e)
{
  Collection<long> c = new Collection<long>();
  Stopwatch s = new Stopwatch();
  s.Start();
  for (long i = 0; i <= 10000000; i++)
  {
    c.Add(i);
  }
  s.Stop();
  MessageBox.Show("collect " + s.ElapsedMilliseconds.ToString());

  List<long> l = new List<long>();
  Stopwatch s2 = new Stopwatch();
  s2.Start();
  for (long i = 0; i <= 10000000; i++)
  {
    l.Add(i);
  }
  s2.Stop();
  MessageBox.Show("lis " + s2.ElapsedMilliseconds.ToString());


}

on my machine List<> is almost twice as fast.

在我的机器列表中,<>几乎是两倍的速度。

Edit

编辑

I can't understand why people are downvoting this. Both on my work machine and my home machine the List<> code is 80% faster.

我不明白为什么人们会反对这样做。在我的工作机器和我的家庭机器上,列表<>代码快了80%。

#6


11  

List represents a collection where the order of items is important. It also supports methods s.a. Sort and search. Collection is a more general data-structure which makes less assumptions about the data and also supports less methods to manipulate it. If you want to expose a custom data structure, you should probably extend the collection. If you need to manipulate data w/o exposing the data-structure, a list is probably the more convenient way to go.

List表示项顺序很重要的集合。它还支持方法s.a. Sort和search。集合是一种更通用的数据结构,它对数据的假设更少,并且支持更少的方法来操作它。如果您想要公开自定义数据结构,那么应该扩展集合。如果您需要操作公开数据结构的数据w/o,那么列表可能是更方便的方法。

#7


4  

This is one of those grad school questions. A Collection of T is sort of abstract; there may be a default implementation (I'm not a .net/c# guy) but a collection will have basic operations like add, remove, iterate, and so on.

这是研究生院的问题之一。T的集合有点抽象;可能有一个默认实现(我不是.net/c#人员),但是集合将具有基本操作,如添加、删除、迭代等等。

List of T implies some specifics about these operations: add should take constant time, remove should take time proportional to the number of elements, getfirst should be consant time. In general, a List is a kind of Collection, but a Collection isn't necessarily a kind of List.

T列表暗示了一些关于这些操作的细节:添加应该花费常数时间,删除应该花费与元素数量成比例的时间,getfirst应该是consant time。一般来说,列表是一种集合,但是集合不一定是一种列表。

#8


4  

Hanselman Speaks: "Collection<T> looks like a list, and it even has a List<T> internally. EVERY single method delegates to the internal List<T>. It includes a protected property that exposes the List<T>."

Hanselman说:“Collection 看起来像一个list,甚至内部还有一个list 。每个方法都委托给内部列表 。它包含一个受保护的属性,该属性公开列表

EDIT: Collection<T> doesn't exist in System.Generic.Collections .NET 3.5. If you migrate from .NET 2.0 to 3.5 you'll need to change some code if you're using a lot of Collection<T> objects, unless I'm missing something obvious...

编辑:集合 在System.Generic中不存在。集合。net 3.5。如果您从。net 2.0迁移到3.5,那么如果您正在使用大量的集合 对象,那么您将需要修改一些代码,除非我遗漏了一些明显的东西……

EDIT 2: Collection<T> is now in the System.Collections.ObjectModel namespace in .NET 3.5. The help file says this:

编辑2:Collection 现在在System.Collections中。. net 3.5中的ObjectModel名称空间。帮助文件是这样写的:

"The System.Collections.ObjectModel namespace contains classes that can be used as collections in the object model of a reusable library. Use these classes when properties or methods return collections."

“System.Collections。ObjectModel名称空间包含可以作为可重用库的对象模型中的集合使用的类。当属性或方法返回集合时使用这些类。

#9


4  

All of these interfaces inherit from IEnumerable, which you should make sure you understand. That interface basically lets you use the class in a foreach statement (in C#).

所有这些接口都继承自IEnumerable,您应该确保理解它。该接口基本上允许您在foreach语句(在c#中)中使用该类。

  • ICollection is the most basic of the interfaces you listed. It's an enumerable interface that supports a Count and that's about it.
  • ICollection是您列出的最基本的接口。它是一个可枚举的接口,支持计数,仅此而已。
  • IList is everything that ICollection is, but it also supports adding and removing items, retrieving items by index, etc. It's the most commonly-used interface for "lists of objects", which is vague I know.
  • IList是ICollection的全部,但它也支持添加和删除项、按索引检索项等。它是“对象列表”最常用的接口,我知道这是模糊的。
  • IQueryable is an enumerable interface that supports LINQ. You can always create an IQueryable from an IList and use LINQ to Objects, but you also find IQueryable used for deferred execution of SQL statements in LINQ to SQL and LINQ to Entities.
  • IQueryable是一个支持LINQ的可枚举接口。您总是可以从IList创建一个IQueryable,并使用LINQ到对象,但是您也可以发现IQueryable用于延迟执行LINQ到SQL的SQL语句,以及将LINQ到实体的SQL语句。
  • IDictionary is a different animal in the sense that it is a mapping of unique keys to values. It is also enumerable in that you can enumerate the key/value pairs, but otherwise it serves a different purpose than the others you listed
  • IDictionary是另一种动物,因为它是唯一键到值的映射。它也是可枚举的,因为您可以枚举键/值对,但否则它的用途与您列出的其他用途不同

#10


4  

According to MSDN, List(Of T).Add is "an O(n) operation" (when "Capacity" is exceeded) while Collection(Of T).Add is always "an O(1) operation". That would understandable if List is implemented using an Array and Collection a Linked List. However, if that were the case, one would expect Collection(Of T).Item to be "an O(n) operation". But - it's - not!?! Collection(Of T).Item is "an O(1) operation" just like List(Of T).Item.

根据MSDN, List(Of T). add是“O(n)操作”(当“容量”被超过),而集合(T). add总是“O(1)操作”。如果使用数组实现List并使用链表集合,则可以理解。但是,如果是这种情况,则可以期望集合(T). item为“O(n)操作”。但是-不是-不是!集合(T). item是O(1)操作,就像列表(T). item。

On top of that, "tuinstoel"'s "Dec 29 '08 at 22:31" post above claims speed tests show List(Of T).Add to be faster than Collection(Of T).Add which I've reproduced with Long's and String's. Although I only got ~33% faster vs. his claimed 80%, according MSDN, it should've been the opposite and by "n" times!?!

除此之外,“tuinstoel”’s“Dec 29’08 at 22:31”发布了以上索赔速度测试清单(T)。增加比收集(T)要快。虽然我只比他声称的80%快了33%,但是根据MSDN的说法,应该是相反的,应该是n次!

#11


3  

Both implement the same interfaces, so they'll behave the same way. Perhaps they are implemented differently internally, but this would have to be tested.

两者实现相同的接口,因此它们的行为方式相同。也许它们在内部执行的方式不同,但这必须经过测试。

The only real differences I see are the namespaces and the fact that Collection<T> is marked with ComVisibleAttribute(false), so COM code can't use it.

我看到的唯一真正的区别是名称空间和集合 被用ComVisibleAttribute(false)标记的事实,所以COM代码不能使用它。

#12


3  

In addition to other asnwers, I've compiled quick overview of generic list and collection capabilities. Collection is limited subset of the List:

除了其他asnwers之外,我还简要概述了通用列表和集合功能。集合是列表的有限子集:

* = present
o = partially present

Property/Method   Collection<T>   List<T>
----------------------------------------------
Add()                *              *
AddRange()                          *
AsReadOnly()                        *
BinarySearch()                      *
Capacity                            *
Clear()              *              *
Contains()           *              *
ConvertAll()                        *
CopyTo()             o              *
Count                *              *
Equals()             *              *
Exists()                            *
Find()                              *
FindAll()                           *
FindIndex()                         *
FindLast()                          *
FindLastIndex()                     *
ForEach()                           *
GetEnumerator()      *              *
GetHashCode()        *              *
GetRange()                          *
GetType()            *              *
IndexOf()            o              *
Insert()             *              *
InsertRange()                       *
Item()               *              *
LastIndexOf()                       *
New()                o              *
ReferenceEquals()    *              *
Remove()             *              *
RemoveAll()                         *
RemoveAt()           *              *
RemoveRange()                       *
Reverse()                           *
Sort()                              *
ToArray()                           *
ToString()           *              *
TrimExcess()                        *
TrueForAll()                        *