我有一个Dictionary使用a double键形成的对象.它看起来像这样:
Dictionary<double, ClassName> VariableName = new Dictionary<double, ClassName>();
Run Code Online (Sandbox Code Playgroud)
我正在使用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);
Run Code Online (Sandbox Code Playgroud)
无论如何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
Run Code Online (Sandbox Code Playgroud)
编辑:删除rowToEdit是一个整数的值,你想删除everthing在哪里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);
Run Code Online (Sandbox Code Playgroud)
试试这个:
var filter = dictionary.Where(x => x.Key - rowToEdit < 1).ToArray();
foreach (var pair in filter)
{
dictionary.Remove(pair.Key);
}
Run Code Online (Sandbox Code Playgroud)