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;
Or you can tell me more nice way? -
For work with selind after total rebuild of _strs i find two way
_strs.Clear(); _strs.Add();
or call again
selind = _strs.Select((name, ind) => new { indexname = name, index = ind }).Where(o => o.indexname == "1");
Can you advice me another way?
Thanks in advance!
Your query:
Is tied to a particular list reference in memory (whatever
_strsis at that time), not to a particular variable name. They are not the same thing. When you do this:You’re not clearing the memory reference of where
_strsoriginally pointed. You are instead having that variable name point to a new memory location. Whereas_strs.Clear()does clear the original list.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.(in case this wasn’t clear,
_strs = nulldoes nothing to the list that_strsused to point to, it just makes that particular variable name invalid)