Mat*_*olf 1 c# iteration ienumerable list
我有以下代码:
foreach (var bar in dataFromDataFeed.Where(bar => bar.Key < fromTicks
|| bar.Key > toTicks))
{
dataFromDataFeed.Remove(bar.Key);
}
Run Code Online (Sandbox Code Playgroud)
这是安全还是我需要将IEnumerable转换foreach为Dictionary<T,U>第一个?
谢谢.
不,那将会炸弹或者让你得到一个仍然有不良元素的结果.只需反转Where表达式:
var filtered = dataFromDataFeed.Where(bar => bar.Key >= fromTicks && bar.Key <= toTicks);
dataFromFeed = filtered.ToList(); // optional
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚你是否真的需要更新列表,因为你有一个非常好的枚举器,所以通常没有必要,所以最后的陈述是// optional.
请记住,像在原始代码中一样使用Remove()具有O(n*m)复杂度,非常糟糕.使用ToList()仅为O(m)但需要O(m)存储.记忆的交易速度是一个常见的程序员的决定,但这是一个灌篮,除非m是巨大的(数亿和你正在对抗OOM)或非常小.考虑到表达,两者都不应该适用.
| 归档时间: |
|
| 查看次数: |
1879 次 |
| 最近记录: |