If we prefer code that is easy to read, using ToList with foreach is appealing. If we prefer a functional style of coding then using RemoveAll may appear neater. ![]() Ultimately, the final choice we make is really a combination of stylistic preferences and performance requirements. But that’s not the case if we are dealing with massive arrays or large numbers of operations. Realistically, in many applications making copies of simple Lists is not really any cause for concern. Whereas the actual data used exists at a class level.Īs we expect, using ToList is very memory intensive due to making copies of the data per iteration. Note that “Allocated” memory measures are used by the method under test. NET/C# content and get paid? > JOIN US! <<Īs a result, we can see that running a raw reverse for loop is easily the most efficient in time and memory. Wanna join Code Maze Team, help us produce more awesome. For this benchmark, we are using a 200 000 integer array and performing 100 iterations of each method. We get these results by running BenchmarkDotNet. We will have a quick look at the performance of these different methods to help us decide what might be best to use: | Method | Mean | Error | StdDev | Allocated | This provides us with a more functional style but is actually no simpler or more compact than a simple foreach loop. We can use this form to operate on each element within the body of the lambda. The return value of this lambda function determines if the element is to be removed. Here we again use the RemoveAll method, but we also use a lambda function as the argument rather than a simple predicate. Fortunately, we can still use RemoveAll in this case by using a lambda function for the predicate: public static List OneLineRemoveAllWithSideEffect(List sourceList) ![]() The only problem with this is that we often need to perform some action on the elements during the iteration. This is a simple, fast, and readable solution that modifies the original list: ![]() We can also use the built-in RemoveAll method with a predicate instead of using a loop. Using RemoveAll to Remove Elements From a Generic List If we saw this in the production code, we might not initially understand why we call ToList() on an object that was already a List. This is effectively identical code to the initial example with the exception that we are now iterating through a copy of the List while removing from the original List. Here we again iterate forward through the list using a foreach loop. However, by simply making a copy of the List using the ToList() method, we can rather use foreach method and iterate forward: public static List SimpleIterateRemoveWithToList(List sourceList) This works well and is easy to understand. Here we iterate backward over the List and call RemoveAt with the index of the element that we wish to remove. Public static List ReverseIterate(List sourceList)įor (int i = sourceList.Count - 1 i >= 0 i-) We can then safely remove elements because they are being removed from the “end” of the List and do not affect the iteration: The simplest solution is to do the same thing as in the naive example, only go backward with a for loop. Using For/Foreach to Remove Elements From a Generic List We will also take a look at the comparative performance of the different methods. We can get around this error in a number of ways depending on what feels clean to us (stylistically). However, this fails with InvalidOperationException. ![]() Here, we define a simple List of numbers in a range and attempt to remove the even elements as we loop through it. Public static List NaiveIterateRemove(List sourceList) If we try simply to do a test and call Remove when we want to discard an element, the solution would throw an exception: private static readonly List _numberList = Enumerable.Range(1, 20).ToList() To download the source code for this article, you can visit our GitHub repository.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |