按值将字典分组

Dividing a dictionary in groups by their values

我有一个 Dictionary<string, int>,其中包含组件 string 和位置 int。现在我想把字典分成四组,每组保存在一个单独的字典中。

group 1 = all positions 1 - 32
group 2 = all positions 33 -64
group 3 = all positions 101 - 132
group 4 = all positions 133 - 164

这就是我目前的情况。

Dictionary<string, int> dictionary = compPos;

填完字典后我就这样点了字典

var items = from pair in dictionary
            orderby pair.Value ascending
            select pair;

我正在考虑使用 for 循环来获取值 <= 32 等的所有组件和位置。但到目前为止,这是我认为可能的唯一方法。

您可以使用ToDictionary()方法创建新词典:

var newDictionary = dictionary.Where(x => x.Value < 32).ToDictionary(d => d.Key, d => d.Value);

编辑:
将 d=> 添加到第二个参数

你可以试试这个:

Dictionary<string, int> dictionary = new Dictionary<string, int>();

dictionary.Add("a", 1);
dictionary.Add("b", 2);
dictionary.Add("c", 34);
dictionary.Add("d", 35);
dictionary.Add("e", 105);
dictionary.Add("f", 106);
dictionary.Add("g", 140);
dictionary.Add("h", 141);

var items = from pair in dictionary
            orderby pair.Value ascending
            select pair;

var list_1_32 = items.Where(v => v.Value >= 1 && v.Value <= 32)
                .ToDictionary(k => k.Key, v => v.Value);
var list_33_64 = items.Where(v => v.Value >= 33 && v.Value <= 64)
                 .ToDictionary(k => k.Key, v => v.Value);
var list_101_132 = items.Where(v => v.Value >= 101 && v.Value <= 132)
                   .ToDictionary(k => k.Key, v => v.Value);
var list_133_164 = items.Where(v => v.Value >= 133 && v.Value <= 164)
                   .ToDictionary(k => k.Key, v => v.Value);

Action<Dictionary<string, int>> print = instance =>
{
  foreach ( var item in instance )
    Console.WriteLine($"{item.Key}: {item.Value}");
};

print(list_1_32);
Console.WriteLine();
print(list_33_64);
Console.WriteLine();
print(list_101_132);
Console.WriteLine();
print(list_133_164);

输出:

a: 1
b: 2

c: 34
d: 35

e: 105
f: 106

g: 140
h: 141