7

I have only two requirements for a data structure:

  • Be read-only,
  • Preserve order (I want to enumerate it in specific order, always).

I know that IReadOnlyList does preserve order. I could use it, but I don't need indexing. That implies I should use IReadOnlyCollection. Unfortunately, I cannot find information that it preserves order.

Do you know if it does?

ebvtrnog
  • 4,167
  • 4
  • 31
  • 59
  • https://msdn.microsoft.com/en-us/library/ms132474%28v=vs.110%29.aspx – rory.ap Apr 28 '16 at 19:29
  • Why can't you use `IEnumerable`? It's the concrete collections which make guarantees about ordering. – Lee Apr 28 '16 at 19:30
  • @roryap It is mentioned that it is a wrapper around `IList`. I'm not sure if it is equivalent to saying that it preserves order... – ebvtrnog Apr 28 '16 at 19:30
  • It does preserve order. – rory.ap Apr 28 '16 at 19:31
  • @Lee I took [this](http://stackoverflow.com/a/32650559/4610370) into account – ebvtrnog Apr 28 '16 at 19:35
  • @Lee And as far as I know IEnumerable does not guarantee to preserve order... – ebvtrnog Apr 28 '16 at 19:36
  • 1
    IEnumerable is an interface that provides methods for enumeration. Nothing about it guarantees order and if you are holding an IEnumerable you should NOT rely on the underlying concrete type if you care about preserving order. You should ask for an IList. For read-only, IReadOnlyList would do. – Suraj Jun 09 '17 at 19:02

1 Answers1

2

For having a readonly list you could follow different approaches.

List<string> list = new List<string>();
IReadOnlyList<string> roList = list;
var roList1 = new ReadOnlyList(list);

roList and roList1 are both readonly, but if you know the original type of roList which is List<string> you can cast it and modify the collection. Thus the second option is the better one. To point out, also a IEnumerable<string> is readonly because it does not provide any methods to modify the collection (if you do not cast it to the original type).

For the second question we can say that any List<T> preserves the order. If you do not want to provide a way to query the list and use OrderBy this is not possible using classes deriving from IEnumerable. This is because of the extension methods. Nevertheless the order in the list instance is preserved, but you can requery. This does not mean that the original list is touched or modifyed.

Michael Mairegger
  • 6,833
  • 28
  • 41
  • I would change "For the second question we can say that any List preserves the order" to "For the second question we can say that any List preserves the item at the index of insertion" to avoid any confusion on the notion of index and order. – Muffun Dec 28 '20 at 21:52