ASP.NET Entity Framework 6 HashSet or List for a collection? ASP.NET Entity Framework 6 HashSet or List for a collection? asp.net asp.net

ASP.NET Entity Framework 6 HashSet or List for a collection?


It depends on your use case but in most cases you can add an item to the collection only once because for example each status is applied only once to a content. I doubt you can have one content appear twice in a status. Therefore HashSet is the correct data structure as it will prevent duplicates. In case where one item can be duplicated List would be correct but I have not encountered this in practice and do not even know how EF would handle it.

As a side note I would advise that you do not include a collection of items in your entities unless you need it. For example if you are building a web app to list products you probably have a view where you display a single product together with its tags. Therefore Product should have a collection of Tags to make this case easy. However you probably do not have a page that displays a Tag with its collection of products and therefore the Tag should not have a Products property. It just doesn't care about related products. It seems that this Status entity does not care about its collection of Contents.


So a HashSet<T> is definition

And a List<T> doesn't have those capabilities.

So I guess it is down to desired characteristics and performance (which on small sets is negligible). They can both be enumerated over.

Performance (although likely tiny differences) will be apparent in two parts, read and write. As Sean commented there will be likely penalties for writes due to hash code calculations and uniqueness comparisons. But reads are extremely fast (o(1)).

So really, it is all down to desired characteristics.

In my projects, I would use List<T>, but that is my sort of convention. You can determine your own convention, as long as you stick to it.