using System.Collections.Generic;
SortedDictionary<CustomKey, string> dict = new SortedDictionary<CustomKey, string>(new KeyComparer());
dict.Add(new CustomKey() { intKey = 1, sortingVariable = 17 }, "1");
dict.Add(new CustomKey() { intKey = 2, sortingVariable = 6 }, "2");
dict.Add(new CustomKey() { intKey = 5, sortingVariable = 12}, "expected value");
dict.Add(new CustomKey() { intKey = 3, sortingVariable = 5 }, "3");
dict.Add(new CustomKey() { intKey = 4, sortingVariable = 4 }, "4");
CustomKey comperativeKey = new CustomKey() { intKey = 5, sortingVariable = 17};
dict.TryGetValue(comperativeKey , out res);
res = dict.Single(kvp => kvp.Key.Equals(comperativeKey)).Value;
public class KeyComparer : Comparer<CustomKey>
public override int Compare(CustomKey x, CustomKey y)
return x.sortingVariable.CompareTo(y.sortingVariable);
public struct CustomKey : IComparable
public override bool Equals(object obj)
return ((CustomKey)obj).intKey == intKey && ((CustomKey)obj).objectKey == objectKey;
public override int GetHashCode()
return intKey.GetHashCode() ^ objectKey.GetHashCode();
public int CompareTo(object obj)
return sortingVariable.CompareTo(((CustomKey)obj).sortingVariable);
public int sortingVariable;
public string otherSortingVariable;