【问题标题】:Need to remove and sort key numbers and color items from dictionary需要从字典中删除和排序关键数字和颜色项目
【发布时间】:2018-09-15 19:53:20
【问题描述】:

我有一个像这样的字典:

var map = new Dictionary<int, ColorType>();

其中 ColorType 是一个枚举 { Red, Yellow, White }

它与一个数字数组配对,例如:

var lstNumbers = Enumerable
            .Range(1, 100).OrderBy(n => Guid.NewGuid().GetHashCode())
            .ToArray();

我需要做以下事情:

  1. 删除所有红色的偶数
  2. 删除所有黄色的奇数
  3. 删除所有可被 3 整除的白色数字
  4. 根据数字升序对列表进行排序,然后颜色(红色

这是一种有效的方法吗?

【问题讨论】:

  • 您的代码效率低下有什么观察结果吗?如果有效,有什么问题?
  • 我不明白lstNumbers 与这个问题的任何内容有什么关系。其中一些操作是针对列表和字典的吗?
  • 您将无法获得比第 4 步中使用的排序方法更高效的方法。排序是一种众所周知的效率,并且没有已知的最快方法的改进。步骤 1-3 都是 O(n),因此与流程的效率无关。
  • 我考虑过使用它,但不确定这是否是正确的方法。 toRemove = lstNumbers.Array .Select(x => new KeyValuePair((int)x.lstNumbers, x.ColorType)) .ToList();

标签: c# arrays dictionary key removeall


【解决方案1】:

对于前 3 个:

foreach(KeyValuePair<int, ColorType> entry in map.ToList()) {

    if (entry.Key % 2 == 0 && entry.Value == ColorType.Red) { // Even and Red
        map.Remove(entry.Key);
    }

    if (entry.Key % 2 == 1 && entry.Value == ColorType.Yellow) { // Odd and Yellow
        map.Remove(entry.Key);
    }

    if (entry.Key % 3 == 0 && entry.Value == ColorType.White) { // Divisible by 3 and White
        map.Remove(entry.Key);
    }
}

至于你的字典排序,可以在here找到答案

【讨论】:

  • 不能同时迭代和修改集合。
  • 是的,我的错,在发布之前没有测试它。更新
  • 您需要遍历字典以打印值或在打印前检查该值是否存在于字典中。
  • @JusteasyStackAttacka 在 cmets 中,将代码块包装在反引号 (` ) 字符中。
  • foreach(var entry in map) { Console.WriteLine($"{entry.Key}, {entry.Value}"); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多