Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What read-only, order-preserving collection in C# should I use to support enumeration?

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?

like image 387
Patryk Golebiowski Avatar asked Nov 09 '22 15:11

Patryk Golebiowski


1 Answers

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.

like image 151
Michael Mairegger Avatar answered Nov 14 '22 23:11

Michael Mairegger