What is the 'best' way to sort (or iterate) over a StringDictionary in order of Value (not Key)
E.g. Key - Value
would give
EDIT - I meant to say "using .NET 2.0 features". Sorry, me bad...
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.
The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Use LINQ:
var items = from k in d.Keys
orderby d[k] ascending
select k;
If you are restricted to C# 2.0 features, use this:
IDictionary<string, string> d = new Dictionary<string, string>();
d["1"] = "X label";
d["2"] = "A label";
d["3"] = "Other Label";
List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(d);
myList.Sort(
delegate(KeyValuePair<string, string> a,
KeyValuePair<string, string> b)
{
return a.Value.CompareTo(b.Value);
}
);
Note: If you are using a StringDictionary instead of Dictionary, check out Anthony's solution.
Using the StringDictionary
class, here is a method to use LINQ's OrderBy
. Assumes you have .NET 3.5.
var sortedDictionary = dictionary.Cast<DictionaryEntry>().OrderBy(pair => pair.Value);
Using 2.0, it's a bit trickier. Here's an approach using a Comparison delegate.
StringDictionary dictionary = new StringDictionary();
dictionary.Add("1", "One");
dictionary.Add("2", "Two");
dictionary.Add("3", "Three");
DictionaryEntry[] sortedDictionary = new DictionaryEntry[dictionary.Count];
dictionary.CopyTo(sortedDictionary, 0);
Comparison<DictionaryEntry> comparison = new Comparison<DictionaryEntry>(delegate (DictionaryEntry obj1, DictionaryEntry obj2) { return ((string)obj1.Value).CompareTo((string)obj2.Value); });
Array.Sort(sortedDictionary, comparison);
So the actual sort would be in the sortedDictionary array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With