开发者

How can i sort the dictionary using keys in c#---Is it possible using LINQ?

    Dictionary<string,string> l_dictData = new Dictionary<string,string>

the above dictionary contains data like this:

    (1)key = "4" value"122"
    (2)key = "8" value"1772"
    (3)key = "0" value"166"

Required output:

   (1)key = "开发者_JAVA技巧0" value"166"
   (2)key = "4" value"122"
   (3)key = "8" value"1772"


Dictionary<TKey, TValue> is inherently unsorted - or at least, the order isn't guaranteed.

SortedList<TKey, TValue> and SortedDictionary<TKey, TValue> are both maps which are sorted by key when you iterate over them. They differ in implementation: SortedList<,> is implemented as a sorted list of key/value pairs, whereas SortedDictionary<,> is a red/black tree. Both have O(log n) search times instead of the O(1) for Dictionary<,> (assuming a decent hash), and other performance complexity measures are different too - the docs for both SortedList<,> and SortedDictionary<,> give details of the different trade-offs between the two.

You can pass in a custom IComparer<T> to determine how the keys should be ordered, but the ordering is always done on key, never on value. It looks like that shouldn't be a problem in the case you've given - although if the keys are actually string values of numbers, you should consider how you want keys "1", "11" and "2" to be ordered...


Depending on how do you want further process the resulting expression (do you want to just print it out ?), it might help to just sort the key value pairs by the key :

foreach(var kvp in l_dictData.OrderBy(k => k.Key))
{ 
     Console.WriteLine("key = {0}, value = {1}", kvp.Key, kvp.Value);
}


You could use a SortedList<string,string>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜