The dictionary int
s I originally generated randomly within a range between 1 - 100 using:
var lstNumbers = Enumerable.Range(1, 100).OrderBy(n => Guid.NewGuid)
.GetHashCode()).ToList();
The dictionary is created and used to assign ColorType
Values to each of the numbers in sequence Red, Yellow, White, Red, Yellow, White, etc., etc. to all of the numbers in the list:
var startColor = ColorType.Red;
var map = new Dictionary<int, ColorType>();
foreach(var number in lstNumbers) {
// First color for assignment
map[number] = startColor.Next();
// Go to the next color
startColor = startColor.Next();
}
I then Remove items a few different ways:
foreach(KeyValuePair<int, ColorType> entry in map.ToList()) {
if (entry.Key % 2 == 0 && entry.Value == ColorType.Red) {
map.Remove(entry.Key);
}
if (entry.Key % 2 == 1 && entry.Value == ColorType.Yellow) {
map.Remove(entry.Key);
}
if (entry.Key % 3 == 0 && entry.Value == ColorType.White) {
map.Remove(entry.Key);
}
}
Then I sort the numbers in ascending order:
foreach(var number in map.OrderBy(i => i.Key)) {
Console.WriteLine(number);
}
Console.ReadLine();
So my list pretty much looks like this now:
[53, Red]
[54, Yellow]
[55, White]
[56, Yellow]
[61, White]
[62, White]
[64, Yellow]
[65, Red]
ect., ect.
Now I need to sort the final list from this dictionary by value with White results being at the top, Yellow in the middle, and red at the bottom. Red < Yellow < White, then display.
I tried this OrderBy
but I may have not implemented it correctly or it might not work for my scenario because I get an error:
The == operator can not be applied to operands of 'ColorType' and 'string'.
foreach(var color in map.OrderBy(c => c.Value == "White" ? 0 : c.Value == "Yellow" ? 1 : 2)) {
Console.WriteLine(color);
}
I tried using IComparer
, but I ran into a problem because I am using a custom type in my dictionary that I use for the colors:
public class CustomerComparer : IComparer<KeyValuePair<int, ColorType>> {
private List<string> orderedColors = new List<string>() { "White", "Yellow", "Red" };
public int Compare(KeyValuePair<int, ColorType> str1, KeyValuePair<int, ColorType> str2) {
return orderedColors.IndexOf(str1.Value) - orderedColors.IndexOf(str2.Value);
}
}
var sorted = map.OrderBy(x => x, new CustomerComparer());
foreach(var entry in sorted) {
Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
}
Console.ReadKey();
I'm guessing there is a better way of doing this, another way, or I am missing something entirely.