Linq: Dictionary - OrderBy with preference Dictionary

本文关键字:Dictionary with preference OrderBy Linq | 更新日期: 2023-09-27 17:55:16

我指的是这个(Linq OrderBy 针对特定值)问题:

我想对一个包含很少值的词典进行排序,以满足我的需求。只有 6 个带有键的条目应该在我的自定义逻辑之后排序。我正在考虑一个数据字典和一个首选项字典:

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,所以一个简单的解决方案将不胜感激。到目前为止谢谢你。

Linq: Dictionary - OrderBy with preference Dictionary

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

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();
您可以使用

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
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);