【问题标题】:Dividing a dictionary in groups by their values将字典按其值分组
【发布时间】:2019-10-09 09:17:41
【问题描述】:

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

第 1 组 = 所有位置 1 - 32
第 2 组 = 所有位置 33 -64
第 3 组 = 所有位置 101 - 132
第 4 组 = 所有位置 133 - 164

这是我目前拥有的。

Dictionary<string, int> dictionary = compPos;

填完字典后,我这样订购了字典。

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

我正在考虑使用 for 循环来获取 value

【问题讨论】:

  • 您可以按将位置 (.Value) 映射到相关组(组 1 到 4)的函数的输出进行分组。

标签: c# dictionary split extraction


【解决方案1】:

您可以使用ToDictionary() 方法创建一个新字典:

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

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

【讨论】:

    【解决方案2】:

    你可以试试这个:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      相关资源
      最近更新 更多