我经常遇到我想在我声明它的地方评估查询的情况.这通常是因为我需要多次迭代它并且计算起来很昂贵.例如:
string raw = "...";
var lines = (from l in raw.Split('\n')
let ll = l.Trim()
where !string.IsNullOrEmpty(ll)
select ll).ToList();
Run Code Online (Sandbox Code Playgroud)
这很好用.但是,如果我不打算修改结果,那么我不妨打电话给ToArray()而不是ToList().
我想知道是否ToArray()通过第一次调用实现,ToList()因此内存效率低于仅调用ToList().
我疯了吗?我应该只是打电话ToArray()- 安全且安全地知道内存不会被分配两次吗?
我正在尝试从字典中构建饼图.在我显示饼图之前,我想整理数据.我正在删除任何小于饼的5%的饼图,并将它们放入"其他"饼图中.但是我Collection was modified; enumeration operation may not execute在运行时遇到异常.
我理解为什么你不能在迭代它们时添加或删除字典中的项目.但是我不明白为什么你不能简单地改变foreach循环中现有键的值.
任何建议:修复我的代码,将不胜感激.
Dictionary<string, int> colStates = new Dictionary<string,int>();
// ...
// Some code to populate colStates dictionary
// ...
int OtherCount = 0;
foreach(string key in colStates.Keys)
{
double Percent = colStates[key] / TotalCount;
if (Percent < 0.05)
{
OtherCount += colStates[key];
colStates[key] = 0;
}
}
colStates.Add("Other", OtherCount);
Run Code Online (Sandbox Code Playgroud)