TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# List RemoveAt Example

This C# example program uses the RemoveAt method on the List type.

RemoveAt removes one element.

How is this method on the List type implemented in the .NET Framework? It requires an index argument. We look at both the usage of RemoveAt and its implementation.

Example. In this program we specify that a List be instantiated with three strings: "dot", "net" and "deves". Next, we remove the string at index 1, which is the second string. The List now contains only two strings: "dot" and "deves".

VarString Literal

C# program that uses RemoveAt

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	var list = new List<string>();
	list.Add("dot");
	list.Add("net");
	list.Add("deves");

	list.RemoveAt(1);

	foreach (string element in list)
	    Console.WriteLine(element);
    }
}

Output

dot
deves

Discussion. My reason for looking at the RemoveAt method was to determine its implementation. Unfortunately, when you call RemoveAt, all the element following the index you remove will be copied and shifted forward.

This is not efficient. If you want to remove an element but eliminate copying, you could simply assign it to null or default(T). Your other code would then have to handle null elements.

NullDefault

Also: The Insert method on List suffers from a similar performance drawback. It causes excessive element copying.

List Insert

Summary. We tested RemoveAt and looked at its internals. RemoveAt will cause all following elements in the list to be copied to new locations in memory. Calling RemoveAt frequently on a large list reduces performance.

Instead: Using a LinkedList or a scheme where null or default elements are treated specially is recommended.

List RemoveLinkedList


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf