-4

I'm trying to do something like this:

Dictionary dict = Dictionary<string, List<string>>();
dict.Add("someKey1", new List<string>());
dict.Add("orange", new List<string>());
dict.Add("foo", new List<string>());

And then when I iterate over the keys, I'd like them to have retained the order as they were added:

foreach(KeyValuePair<string, string> entry in myDictionary)
{
    Console.WriteLine(entry.Key);
}

Should print out:

someKey1
orange
foo

I know that c# Dictionary keys don't retain their order as they were added, so is there another way I can do this so that the keys retain their order?

u84six
  • 4,604
  • 6
  • 38
  • 65
  • 2
    Queue class is worth a look: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1?view=netframework-4.7.2 – MacroMarc Oct 05 '18 at 18:28
  • 2
    Possible Duplicate: https://stackoverflow.com/questions/16694182/ordereddictionary-and-dictionary – Evan M Oct 05 '18 at 18:28

2 Answers2

2

A generic ordered dictionary does not exist in .NET, but you could use the OrderedDictionary class instead. See MSDN

adjan
  • 13,371
  • 2
  • 31
  • 48
  • This is not generic. I need a way to keep the keys ordered as they were added and also be able to create values of type List. – u84six Oct 05 '18 at 18:51
  • Yes I did read, there is no generic way, only the `OrderedDictionary`. Else you have to implement it on your own or use thrid party classes – adjan Oct 05 '18 at 19:04
-1

Use Queue class from System.Collections.Generic to ensure the order.

// Create queue
Queue<TestItem> queue = new Queue<TestItem>();
// Add item
queue.Enqueue(new TestItem { });
// Fetch item
queue.Dequeue();