1

I am refering to this (Linq OrderBy against specific values) question:

I want to sort a Dictionary with very few values suiting my needs. There will only be 6 entries with keys that should be sorted after my custom logic. I am thinking about one data-dictionary and one pref-dictionary:

Dictionary<string, int> data = new Dictionary<string,int>() {
        {"Test16", 10},
        {"What61", 8}, 
        {"Blub11", 14},
        {"Int64", 13}
    };

Dictionary<string, int> preferences = new Dictionary<string, int>() {
        {"Blub11", 1},
        {"What61", 2},
        {"Int64", 3},
        {"Test16", 4}
    };

// desired Output:
// data =
//  {"Blub11", 14},
//  {"What61", 8},
//  {"Int64", 13},
//  {"Test16", 10}

string key;
data = data.OrderBy(
    item => preferences.TryGetValue(item, out key) ? data[key] : item
);

I can't get this to work and must admit that I am not familiar with lambda expressions and linq so a simple solution would be appreciated. Thank you so far.

Community
  • 1
  • 1

3 Answers3

2

You can do the following (if preferences key always exist):

KeyValuePair<string, int>[] orderedData = data.OrderBy(p => preferences[p.Key])
                                              .ToArray();

If it is possible for key not to exist in preferences, you can check for that:

KeyValuePair<string, int>[] orderedData = data.OrderBy(p => preferences.ContainsKey(p.Key) ? preferences[p.Key] : int.MaxValue)
                                              .ToArray();
Ulugbek Umirov
  • 12,719
  • 3
  • 23
  • 31
0

You can use IOrderedEnumerable<KeyValuePair<string, int>>:

IOrderedEnumerable<KeyValuePair<string, int>> sortedValues 
                                            = data.OrderBy(r => r.Value);

Then for output:

foreach (var item in sortedValues)
{
    Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

Output:

Key: What61, Value: 8
Key: Test16, Value: 10
Key: Int64, Value: 13
Key: Blub11, Value: 14
Habib
  • 219,104
  • 29
  • 407
  • 436
-1
var result = data.Join
    (
        preferences,
        x=>x.Key,
        x=>x.Key,
        (d,p)=>new {d.Key,d.Value,OrderBy = p.Value}
    )
    .OrderBy(x=>x.OrderBy)
    .ToDictionary(k=>k.Key,v=>v.Value);
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69