1

I am using dictionary to collect some information. After I collect the details I need to sort the dictionary values based on the key using var Variable. After that I need to insert the sorted var variable to the new dictionary. Here, I have trouble to insert the sorted data into dictionary.

I'm posting my code Here:

var  orderDic = from dic in dictionaryColl
                orderby dic.Key  ascending
                select dic;             
Dictionary<int, string> newDic = new Dictionary<int, string>();
newDic =(Dictionary<int,string>)orderDic;  // Here i'm not able to assign data to dictionary

Thanks in Advance..

4u.Ans
  • 1,279
  • 14
  • 22
Sivaperuman
  • 239
  • 1
  • 4
  • 21
  • 1
    Dictionaries are unsorted by nature. They use a hash function to hash the key to get an entry for the value. There is a sorted dictionary data structure available in .net that you might want to use – devshorts May 20 '13 at 12:15

5 Answers5

4

You can directly convert it to dictionary like:

Dictionary<int, string> newDic  = (from dic in dictionaryColl
                                  orderby dic.Key ascending
                                  select dic)
                                 .ToDictionary(r => r.Key, r => r.Value);

Or with method syntax:

Dictionary<int, string> newDic = dictionaryColl
                                .OrderBy(r => r.Key)
                                .ToDictionary(r => r.Key, r => r.Value);

EDIT: OrderBy would not effect the retrieval of Dictionary items in order.

See: Dictionary<TKey, TValue> Class

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.

What you need is SortedDictionary like:

SortedDictionary<int, string> sortedNewDic = 
           new SortedDictionary<int, string>(dictionaryColl);
Habib
  • 219,104
  • 29
  • 407
  • 436
3

You just need

newDic = orderDic.ToDictionary(x=> x.Key, x => x.Value);

However this will not really help much as the order by clause won't affect the dictionary order.

It's possible you want a SortedDictionary?

new Dic = new SortedDictionary(dictionaryColl);
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • @Habib no it won't. The order of a dictionary is non-deterministic - see the accepted answer from this [SO](http://stackoverflow.com/questions/4007782/the-order-of-elements-in-dictionary) – Bob Vale May 20 '13 at 12:16
0

Why don't you use SortedDictionary at first place (http://msdn.microsoft.com/en-us/library/f7fta44c.aspx) ?

Sumit Gupta
  • 2,152
  • 4
  • 29
  • 46
0
newDic =(Dictionary<int,string>).OrderBy(l => l.ColName).ToList();

Where ColName is name of column you want to apply sorting or ordering.

nawfal
  • 70,104
  • 56
  • 326
  • 368
Hisham
  • 455
  • 4
  • 16
-2

You can use

var _ordered = _dic.OrderBy(d => d.key).ToDictionary(d => d.Key, d => d.Value); 

method to order the dictionary in ascending order.

or

you can use

var _ordered = _dic.OrderByDescending(d => d.key).ToDictionary(d => d.Key, d => d.Value); 

method to order the dictionary in descending order.

Or else if you want to replace the same dictionary then

var _ordered = _dic.OrderByDescending(d => d.key).ToDictionary(d => d.Key, d => d.Value); 

in case your original Dictionary is _dic

_dic=new Dictionary<int, string>(_ordered);

Please go through the following code,

class Program
{
    static void Main(string[] args)
    {
        Dictionary<int,string> _dic=new Dictionary<int,string>();
        _dic.Add(5,"xyz");
        _dic.Add(2,"abc");
        _dic.Add(1,"pqr");
        _dic.Add(4,"test");
        _dic.Add(3,"pvf");

        var _ordered=_dic.OrderBy(d => d.Key).ToDictionary(d=> d.Key,d=>d.Value);
        _dic=new Dictionary<int,string>(_ordered);
    }
}

You can debug the above application and check that _dic is having the sorted dictionary based on the key.

nawfal
  • 70,104
  • 56
  • 326
  • 368
  • 1
    As already stated, ordering the items before inserting into a dictionary doesn't help. Dictionary is unordered. Use a SortedDictioanry instead – Bob Vale May 20 '13 at 12:25
  • I am storing the sorted dictionary in a new Dictionary, like in the query it is mentioned to get the result in var and then store it to another dictionary. Here I am skipping the use of Var and directly storing the dictionary in the new instance of Dictionary<,>() – Prabhanjan Kumar Mahapatra May 20 '13 at 12:31
  • The point is the dictionary will not be in Ascending order. Dictionaries are not sorted. The orderby will have no effect – Bob Vale May 20 '13 at 12:35
  • So what, the OrderBy method will sort the Dictionary in ascending order of the key in the above statement. If the Dictionary will be in Ascending order then what is the use of sorting the dictionary??? – Prabhanjan Kumar Mahapatra May 20 '13 at 12:38
  • The orderBy sorts the the IEnumerable result. There is no point in sorting the dictionary. Thats the point. The dictionary will ignore your order by. You need a different solution, like SortedDictionary – Bob Vale May 20 '13 at 12:52