WP7 SortedDictionary
-
03-07-2021 - |
Question
I understand that SortedDictionary is not available in WP7...so have to sort it yourself.
I have found a number of examples and am currently using this code
Dictionary<string, TimetableClass> AllClasses = new Dictionary<string, TimetableClass>()
{
{ "Maths", new TimetableClass {ClassName="Maths", Location="RM1"}},
{ "Physics", new TimetableClass {ClassName="Physics", Location="PM1"}},
{ "English", new TimetableClass {ClassName="English", Location="PM1"}},
{ "Algebra", new TimetableClass {ClassName="Algebra", Location="A1"}}
};
var sortedDict = new Dictionary<string, TimetableClass>();
foreach (KeyValuePair<string, TimetableClass> singleclass in AllClasses.OrderBy(key => key.Value))
{
sortedDict.Add(singleclass.Key, singleclass.Value);
}
But when I run this I get an exception on the foreach?
Exception is an Unhandled Argument Exception - "Value does bot fall within the expected range"
Really have no idea what I have done wrong here. Any help appreciated.
- Thanks
Solution
This should work
foreach (KeyValuePair<string, TimetableClass> singleclass in AllClasses.OrderBy(item => item.Key))
{
sortedDict.Add(singleclass.Key, singleclass.Value);
}
Alternately, if you want to sort based on Object(Value), try this
foreach (KeyValuePair<string, TimetableClass> singleclass in AllClasses.OrderBy(item => item.Value.ClassName))
{
sortedDict.Add(singleclass.Key, singleclass.Value);
}
And finally, you can also avail this instead of a foreach loop and without the need of an extra 'sortedDict' dictionary.
AllClasses = AllClasses.OrderBy(item => item.Key).ToDictionary(item => item.Key, item => item.Value);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow