0

I have: Dictionary<int, int> Color_Count = new Dictionary<int, int>();

and also: var sortedDict = from entry in Color_Count orderby entry.Value descending select entry;

But I don't know how to fix this compiler error. When I am trying to copy keys from this dictionary to integer massive, like this:

int[] Colors_massive = sortedDict.Keys.ToArray();

It cause error CS1061:

'System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<int,int>>' does not contain a definition for 'Keys' and no extension method 'Keys' accepting a first argument of type 'System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<int,int>>' could be found (are you missing a using directive or an assembly reference?)   

If I am trying to copy, using other method:

int[] Colors_massive = new int[sortedDict.Keys.Count];
        sortedDict.Keys.CopyTo(Colors_massive, 0);

It also cause same error, but now error is printed twice. If I replace word 'Keys' in code, for word 'Values', it also prints the same error, but now compiler cannot find the definition for 'Values'.

What am I doing wrong here?

Ganesh R.
  • 4,337
  • 3
  • 30
  • 46
Dreamov
  • 3
  • 2

2 Answers2

1

What your statement does is return a IEnumerable (System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<int,int>>).

IEnumerable does not have a property called Key or Value. It only allows you to interate through the contents.

You are just ordering the contents of the dictionary by its values.

Try this:

    Dictionary<int, int> Color_Count = new Dictionary<int, int>();
    List<KeyValuePair<int, int>> sortedDict = Color_Count.OrderByDescending(entry => entry.Value).ToList();
    int[] Colors_massive = sortedDict.Select(x => x.Key).ToArray();
    List<int> orderedValues = sortedDict.Select(x => x.Value).ToList();
Ganesh R.
  • 4,337
  • 3
  • 30
  • 46
0

You can use the other form of LINQ to keep the thing simple

var sortedDict = Color_Count.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

The sortedDict is then still a dictionary and you can access it's Keys collection

If you just want to create an array of keys, then it's even more simple

int[] sorted = Color_Count.OrderByDescending(x => x.Value).Select(x => x.Key).ToArray();
VladL
  • 12,769
  • 10
  • 63
  • 83
  • Isn't the order lost as you convert the sorted list back to a dictionary? – Ganesh R. May 10 '15 at 09:18
  • @GaneshR. no, it isn't as you create the dictionary from the subset returned by `OrderByDescending` – VladL May 10 '15 at 09:20
  • Order in dictionary is non deterministic. It works in a test I created but not guaranteed. http://stackoverflow.com/questions/4007782/the-order-of-elements-in-dictionary – Ganesh R. May 10 '15 at 09:30
  • @GaneshR. I know, it could be different in another .NET implementation, but Microsoft has always implemented the dictionary this way. – VladL May 10 '15 at 09:36