Skip to content

Instantly share code, notes, and snippets.

@noahmorrison
Last active August 29, 2015 14:24
Show Gist options
  • Save noahmorrison/4d1d2488e6d6a75f3938 to your computer and use it in GitHub Desktop.
Save noahmorrison/4d1d2488e6d6a75f3938 to your computer and use it in GitHub Desktop.
C# dictionary ordering
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DictionaryOrderTest
{
class Program
{
static void Main(string[] args)
{
Console.Write("Testing without deletions or extra insertions: ");
Console.WriteLine(Test(false, false) ? "Passed" : "Failed");
Console.Write("Testing with deletions and no extra insertions: ");
Console.WriteLine(Test(true, false) ? "Passed" : "Failed");
Console.Write("Testing with deletions and extra insertions: ");
Console.WriteLine(Test(true, true) ? "Passed" : "Failed");
Console.Write("Testing without deletions and with extra insertions: ");
Console.WriteLine(Test(false, true) ? "Passed" : "Failed");
Console.ReadKey();
}
static bool Test(bool doDelete, bool doInsert)
{
var dict = new Dictionary<string, object>();
var list = new List<string>();
var rand = new Random();
for (var i = 0; i < 1000000; i++)
{
var key = rand.Next().ToString();
try
{
dict.Add(key, null);
list.Add(key);
}
catch (ArgumentException)
{ i--; }
}
if (doDelete)
{
dict.Remove(dict.Keys.First());
list.Remove(list.First());
}
if (doInsert)
{
dict.Add("Another", null);
list.Add("Another");
}
var idx = 0;
foreach (var pair in dict)
if (pair.Key != list[idx++])
return false;
return true;
}
}
}
Testing without deletions or extra insertions: Passed
Testing with deletions and no extra insertions: Passed
Testing with deletions and extra insertions: Failed
Testing without deletions and with extra insertions: Passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment