c# - 如何使用 Int 删除作为 Double 的 Dictionary 行?

标签 c# dictionary

我有一个 Dictionary使用 double 形成的对象作为它的关键。它看起来像这样:

Dictionary<double, ClassName> VariableName = new Dictionary<double, ClassName>();

我正在使用 double作为键类型,因为我要求键看起来像这样:1.1、1.2、2.1、2.2 等。

我系统中的所有内容都运行良好,除非我想删除组中的所有键,例如,所有 1 值都是 1.1、1.2 等。

如果我知道键的完整值,例如 1.1,我可以删除行,但在我的系统中,我只会知道整数。

我尝试执行以下操作,但出现错误:
DictionaryVariable.Remove(j => Convert.ToInt16(j.Key) == rowToEdit).OrderByDescending(j => j.Key);

是否有根据 int 删除所有行?通过转换键值?

最佳答案

一、考虑使用 Decimal 而不是 Double . Double 是浮点数,不适合精确比较(这对于键值查找至关重要)。您仍然可以处理 1.1 或 2.2 等数字。

其次,你需要的是:

dictionary.Remove(rowToEdit); // where rowToEdit is the
                              // key of the key-value par you want
                              // to remove

编辑 :删除 rowToEdit 是整数的值,并且您想要删除 rowToEdit <= k < (rowToEdit + 1) 的所有内容
var removedKeys = x.Keys
    .Where(k => k >= 0 ? Math.Floor(k) : Math.Ceiling(k) == rowToEdit).ToArray();
foreach (var key in removedKeys) dictionary.Remove(key);

关于c# - 如何使用 Int 删除作为 Double 的 Dictionary 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2652748/

相关文章:

python - 从 Pandas 数据框创建嵌套字典

c# - 无法读取文件中被另一个进程使用的所有行

c# - 在存储库模式中使用通用接口(interface)

c# - 如何在 .net 中读取 SQL Server 架构信息?

python - 使用元组中的一个键访问字典键和值

python - 使用map和lambda来模拟字典理解

c# - 使用 C# 和 Aster.NET 可靠地识别和跟踪 Asterisk 调用

c# - C# 可执行文件的 Ngen 输出不是有效的 Win32 应用程序

python - 从 pandas DataFrame 中提取对的最佳方法

Python:将嵌套字典列出到 pandas DataFrame 问题