Linq:Dictionary - OrderBy with preference Dictionary

时间:2014-03-31 14:54:04

标签: c# linq dictionary sql-order-by

我正在引用这个(Linq OrderBy against specific values)问题:

我想用很少的值来排序一个符合我需求的词典。只有6个条目的键应该在我的自定义逻辑之后排序。我正在考虑一个数据字典和一个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
);

我不能让这个工作,并且必须承认我不熟悉lambda表达式和linq,所以一个简单的解决方案将不胜感激。谢谢你到目前为止。

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作(如果首选项键始终存在):

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

如果密钥可能不存在于首选项中,您可以检查:

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

答案 1 :(得分:0)

您可以使用IOrderedEnumerable<KeyValuePair<string, int>>

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

然后输出:

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

输出:

Key: What61, Value: 8
Key: Test16, Value: 10
Key: Int64, Value: 13
Key: Blub11, Value: 14

答案 2 :(得分:-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);
相关问题