What are differences between Collection and List in C#. I mean which one should I use in navigation properties:
public Collection<OrderDetail> OrderDetails { get; set; }
OR
public List<OrderDetail> OrderDetails { get; set; }
CodePudding user response:
There appear to be no docs for this, but Entity Framework supports any IEnumerable<T>
for collection navigation properties.
So you can just declare them as:
IEnumerable<T>
ICollection<T>
Collection<T>
HashSet<T>
IList<T>
List<T>
And probably more. As far as Entity Framework is concerned, there's no difference, it'll assign the appropriate one at runtime and can do all it does with each one, apart from calling AddRange()
on most of them, but when do you want to use that?
If you want databinding, you could use an ObservableCollection<T>
, for example, otherwise I'd go with the leanest interface that still allows adding items: ICollection<T>
.
CodePudding user response:
The entity frameworks supports the Collections
more effective than the List
. So better use Collection for your usage.
List
represents a collection where the order of items is important. It also supports methods such as Sort and search.
Whereas 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.
If you want to expose a custom data structure, you should probably extend the collection.