【问题标题】:Blow dictionary out to a list将字典吹出列表
【发布时间】:2011-04-06 23:23:54
【问题描述】:

我有一本带有这个签名的字典:

Dictionary<decimal, int>

里面的物品是这样的:

90, 2
60, 3
30, 4
20, 1

我需要将其添加到具有此签名的列表中:

List<double>

里面的物品看起来像这样:

90
90
60
60
60
30
30
30
30
20

关于如何以优雅高效的方式做到这一点的任何想法?

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

    试试下面的

    dictionary
      .SelectMany(pair => Enumerable.Repeat((double)pair.Key, pair.Value))
      .OrderByDescending(x => x)
      .ToList();
    

    【讨论】:

    • 我不确定 OrderBy 是否是要求的一部分。
    • @spender,OP 没有指定但将元素按顺序排列,所以我在确保我的输出匹配时出错。
    • 是的,我想鉴于字典的枚举顺序没有定义,OP 需要注意 SelectMany 之前或之后的排序(就像你所做的那样)。跨度>
    • 我希望我能 + 超过 1 个。很好的答案
    【解决方案2】:
    dictionary
        .SelectMany(kvp => Enumerable.Repeat(Decimal.ToDouble(kvp.Key), kvp.Value))
        .ToList()
    

    【讨论】:

      【解决方案3】:
      foreach (var pair in dict)
          for (int i=0;i<pair.Value;i++)
              list.Add((double)pair.Key);
      

      【讨论】:

        【解决方案4】:
        public static IEnumerable<T> Blowout<T>(T value, int length)
        {
            for (int i = 0; i < length; i++) yield return value;
        }
        
        dictionary
            .SelectMany(pair => Blowout((double)pair.Key, pair.Value));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-19
          • 2017-04-23
          • 2021-10-13
          • 2015-07-23
          • 1970-01-01
          • 2018-08-21
          • 1970-01-01
          相关资源
          最近更新 更多