List (of T)와 Collection (of T)의 차이점은 무엇입니까?
나는 그것들이 같은 방식으로 많이 사용되는 것을 보았고, 내가 이것을 더 잘 이해하지 못하면 되돌릴 수없는 디자인의 길을 갈까 걱정된다. 또한 .NET을 사용하고 있습니다.
Collection<T>
주위에 사용자 정의 가능한 래퍼 IList<T>
입니다. 동안 IList<T>
밀폐되지 않은, 어떤 사용자 정의 포인트를 제공하지 않습니다. Collection<T>
의 메서드는 기본적으로 표준 IList<T>
메서드에 위임 되지만 원하는 작업을 수행하도록 쉽게 재정의 할 수 있습니다. Collection<T>
IList로 할 수 있다고 생각하지 않는 이벤트를 내부에 연결하는 것도 가능합니다 .
요컨대, 사실 이후에 확장하는 것이 훨씬 쉬우므로 잠재적으로 리팩토링이 훨씬 줄어들 수 있습니다.
C #에는 개체 모음을 나타내는 세 가지 개념이 있습니다. 기능 증가 순서는 다음과 같습니다.
- 열거 가능 -정렬되지 않고 수정할 수 없음
- 컬렉션 -항목 추가 / 제거 가능
- 목록 -항목이 순서를 가질 수 있도록 허용합니다 (인덱스로 액세스 및 제거).
Enumerable 에는 순서가 없습니다. 세트에서 항목을 추가하거나 제거 할 수 없습니다. 세트의 항목 수를 얻을 수도 없습니다. 세트의 각 항목에 차례로 액세스 할 수 있습니다.
컬렉션 은 수정 가능한 집합입니다. 세트에서 객체를 추가 및 제거 할 수 있으며 세트의 항목 수를 가져올 수도 있습니다. 그러나 여전히 순서가없고 순서가 없기 때문에 인덱스로 항목에 액세스 할 수없고 정렬 할 방법도 없습니다.
목록 은 정렬 된 개체 집합입니다. 목록을 정렬하고, 인덱스로 항목에 액세스하고, 인덱스로 항목을 제거 할 수 있습니다.
실제로 이러한 인터페이스를 살펴보면 서로를 기반으로 구축됩니다.
interface IEnumerable<T>
GetEnumeration<T>
interface ICollection<T> : IEnumerable<T>
Add
Remove
Clear
Count
interface IList<T> = ICollection<T>
Insert
IndexOf
RemoveAt
변수 또는 메소드 매개 변수를 선언 할 때 다음을 사용하도록 선택해야합니다.
- IEnumerable
- ICollection
- IList
개념적으로는 개체 집합을 처리해야합니다.
목록의 모든 개체에 대해 무언가를 수행 할 수 있어야한다면 다음 만 필요합니다 IEnumerable
.
void SaveEveryUser(IEnumerable<User> users)
{
for User u in users
...
}
[사용자가에 보관하는 경우 상관 없어 List<T>
, Collection<T>
, Array<T>
다른 사람 또는 아무것도. IEnumerable<T>
인터페이스 만 필요합니다 .
세트에서 항목을 추가, 제거 또는 계산할 수 있어야하는 경우 컬렉션 을 사용하십시오 .
ICollection<User> users = new Collection<User>();
users.Add(new User());
정렬 순서에 관심이 있고 올바른 순서가 필요한 경우 List 를 사용하십시오 .
IList<User> users = FetchUsers(db);
차트 형식 :
| 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 |
List<T>
과 Collection<T>
에서 System.Collections.Generic
이 인터페이스를 구현하는 두 개의 클래스가 있습니다; 그러나 그들은 유일한 수업이 아닙니다.
ConcurrentBag<T>
주문한 개체 가방입니다 (IEnumerable<T>
).LinkedList<T>
색인 (ICollection
)으로 항목에 액세스 할 수없는 가방입니다 . 하지만 컬렉션에서 항목을 임의로 추가 및 제거 할 수 있습니다.SynchronizedCollection<T>
인덱스별로 항목을 추가 / 제거 할 수있는 정렬 된 컬렉션
따라서 다음을 쉽게 변경할 수 있습니다.
IEnumerable<User> users = new SynchronizedCollection<User>();
SaveEveryUser(users);
tl; dr
- 열거 가능 -정렬되지 않고 수정할 수없는 액세스 항목
- 컬렉션 -수정 가능 (추가, 삭제, 개수)
- 목록 -색인으로 액세스 가능
선택 개념 당신이 필요를, 다음 일치하는 클래스를 사용합니다.
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).
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.
The above are just recommendations.
[Adapted from: Framework Design Guidelines, Second Edition]
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).
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.
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.
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.
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.
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.
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.
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>
."
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...
EDIT 2: Collection<T>
is now in the System.Collections.ObjectModel namespace in .NET 3.5. The help file says this:
"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."
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#).
ICollection
is the most basic of the interfaces you listed. It's an enumerable interface that supports aCount
and that's about it.IList
is everything thatICollection
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.IQueryable
is an enumerable interface that supports LINQ. You can always create anIQueryable
from an IList and use LINQ to Objects, but you also findIQueryable
used for deferred execution of SQL statements in LINQ to SQL and LINQ to Entities.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
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.
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!?!
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.
In addition to other asnwers, I've compiled quick overview of generic list and collection capabilities. Collection is limited subset of the List:
* = 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() *
'program story' 카테고리의 다른 글
Eclipse가 시작되지 않음-Java 가상 머신을 찾을 수 없음 (0) | 2020.09.13 |
---|---|
UIVisualEffectView 및 / 또는 UIBlurEffect를 페이드 인 및 아웃하는 방법은 무엇입니까? (0) | 2020.09.13 |
Qt 이벤트 및 신호 / 슬롯 (0) | 2020.09.13 |
node-jwt-simple이있는 passport-local (0) | 2020.09.12 |
ELF 파일과 bin 파일의 차이점은 무엇입니까? (0) | 2020.09.12 |