Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. List<T>.Insert() / Count

List<T>.Insert() / Count

The Insert() method inserts an element at a specified position in a list, and the Count property returns the current number of elements in the list.

Syntax

using System.Collections.Generic;

// Inserts an element at the specified index.
list.Insert(int index, T item)

// Inserts all elements of a collection at the specified index.
list.InsertRange(int index, IEnumerable<T> collection)

// Gets the current number of elements in the list.
list.Count

Member List

MemberDescription
Insert(int index, T item)Inserts an element at the specified index. All subsequent elements are shifted back by one.
InsertRange(int index, IEnumerable<T> collection)Inserts all elements of a collection at the specified index.
CountReturns the current number of elements in the list as an integer. Updated automatically whenever elements are added or removed.

Sample Code

using System;
using System.Collections.Generic;

// Create a List<string> with initial values.
List<string> ranking = new List<string> { "Tanaka", "Sato", "Suzuki" };
Console.WriteLine($"Count: {ranking.Count}"); // Count: 3

// Use Insert() to insert at index 1.
ranking.Insert(1, "Yamada");
Console.WriteLine(string.Join(", ", ranking)); // Tanaka, Yamada, Sato, Suzuki
Console.WriteLine($"Count: {ranking.Count}"); // Count: 4

// Insert at the beginning (index 0).
ranking.Insert(0, "Ito");
Console.WriteLine(string.Join(", ", ranking)); // Ito, Tanaka, Yamada, Sato, Suzuki

// Use InsertRange() to insert multiple elements at once.
List<int> numbers = new List<int> { 1, 5 };
numbers.InsertRange(1, new int[] { 2, 3, 4 }); // Insert at index 1.
Console.WriteLine(string.Join(", ", numbers)); // 1, 2, 3, 4, 5

// Example of using Count in a loop.
List<int> evens = new List<int>();
for (int i = 2; i <= 10; i += 2)
{
    evens.Add(i);
}
Console.WriteLine($"Even count: {evens.Count}"); // Even count: 5

Notes

Count is the list equivalent of the array Length property. Because List<T> does not have a Length property, calling Length by mistake — confusing it with an array — will cause a compile error. Always use Count to get the number of elements in a list.

Insert() must shift all elements after the insertion point, so the larger the list, the higher the processing cost. If you frequently need to insert at the beginning or in the middle of a collection, consider using LinkedList<T> instead.

For searching and checking elements, see 'List<T>.Contains() / IndexOf()'.

If you find any errors or copyright issues, please .