在LINQ中使用挂起的请求时,信息保存在内存中 [英] Information saved in memory when using pending request in LINQ
问题描述
我正在学习LINQ,并且我想使用待处理的请求,但是我遇到了这个问题
I learning LINQ, and i want to use pending request, but i have this problem
List<string> _strs = new List<string> { "1", "2", "1", "1", "0" };
var selind = _strs.Select((name, ind) => new { indexname = name, index = ind }).Where(o => o.indexname == "1");
string sind = "";
foreach (var item in selind)
sind += item.index.ToString() + " ";
//i get 0 2 3
_strs.Add("2");
_strs.Add("1");
sind = "";
foreach (var item in selind)
sind += item.index.ToString() + " ";
//Good, i get 0 2 3 6
_strs = new List<string>() { "1" };
sind = "";
foreach (var item in selind)
sind += item.index.ToString() + " ";
//Why i get again 0 2 3 6
好的,我理解为什么,但是我很想知道两件事:
Ok i understand why, but I wolud like to know two things:
-
我应该如何清除内存?
How should i clear memory?
selind = null; 还是可以告诉我更多更好的方法?
selind = null; Or you can tell me more nice way?
要在完全重建_strs后使用selind,我会找到两种方法
For work with selind after total rebuild of _strs i find two way
_strs.Clear();
_strs.Add();
或再次致电
selind = _strs.Select((name, ind) => new { indexname = name, index = ind }).Where(o => o.indexname == "1");
您能以另一种方式建议我吗?
Can you advice me another way?
提前谢谢!
推荐答案
您的查询:
_strs.Select((name, ind) => new { indexname = name, index = ind }).Where(o => o.indexname == "1");
绑定到内存中的特定列表引用(无论当时的_strs
是什么),而不是特定的变量名称.它们不是同一件事.当您这样做时:
Is tied to a particular list reference in memory (whatever _strs
is at that time), not to a particular variable name. They are not the same thing. When you do this:
_strs = new List<string>() { "1" };
您不会清除_strs
最初指向的内存引用.取而代之的是,让该变量名指向新的内存位置.而_strs.Clear()
确实清除了原始列表.
You're not clearing the memory reference of where _strs
originally pointed. You are instead having that variable name point to a new memory location. Whereas _strs.Clear()
does clear the original list.
针对您的问题的最佳解决方案是将LINQ查询包装在接受列表的函数中,因此您可以在新列表上再次调用它而无需再次键入.另外,根据您的使用情况,在需要再次启动时只需调用.Clear()
.
The best solution for your problem is to wrap the LINQ query in a function that accepts a list, so you can call it again on new lists without typing it again. Alternatively, depending on your use case, just call .Clear()
when you need to start again.
(如果不清楚,_strs = null
对_strs
所指向的列表不执行任何操作,只会使该特定变量名称无效)
(in case this wasn't clear, _strs = null
does nothing to the list that _strs
used to point to, it just makes that particular variable name invalid)
这篇关于在LINQ中使用挂起的请求时,信息保存在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!