I am attempting to lean linq by replacing existing code in a project with linq calls. In this method I check for a condition in my list of lines and if the condition is true, move that element from lines to processedLines.
The data structures are just lists:
List<LineSegment2> lines;
List<LineSegment2> processedLines;
The original code was:
for (int i = lines.Count - 1; i >= 0; i--)
{
if (lines[i].P2.x < sweepPosition)
{
processedLines.Add(lines[i]);
lines.RemoveAt(i);
}
}
and my linq code is:
var toMove = lines.FindAll(x => x.P2.x < sweepPosition);
toMove.ForEach(x =>
{
processedLines.Add(x);
lines.Remove(x);
});
My question is: Is this linq code less efficient because it is using more memory creating the temporary list ‘toMove’. Is there a way to create the linq query without requiring the temporary list or is the original code always more efficient?
A more LINQy solution would be to add all the processed lines at once, then get the remaining lines:
As for efficiency, it won’t be quite as fast as your original code. That’s not why you use LINQ.
There is one potential advantage, though. It will make a new list of lines, so if you move a lot of lines to the processed list it will get rid of the unused items in the list.