How to initialize a list in C#, with existing array
xxxxxxxxxx
int[] initialArray = { 1, 2, 3, 4 };
List<int> numbers = new List<int>(initialArray);
xxxxxxxxxx
List<string> myListOfStrings = new List<string>
{
"this",
"is",
"my",
"list"
};
xxxxxxxxxx
using System.Collections.Generic;
private List<string> list; //creates list named list of type string
list.Add(string); //adds string at last index of list
list.Count; //get length of list
list.Insert(2,"pos 2"); // Insert string "pos 2" in position 2
list[i]; //get item from index i
xxxxxxxxxx
// List with default capacity
List<Int16> list = new List<Int16>();
// List with capacity = 5
List<string> authors = new List<string>(5);
string[] animals = { "Cow", "Camel", "Elephant" };
List<string> animalsList = new List<string>(animals);
xxxxxxxxxx
List<int> numbers = new List<int>();
// Add/Remove Elements from a List
numbers.Add(1);
numbers.Remove(1);
// Access Elements
int firstNumber = numbers[0];
Console.WriteLine(firstNumber); // Output = 1
// Collection of Elements:
List<string> colors = new List<string> { "coal", "emerald", "sapphire" };
// Generic Uses
int count = numbers.Count;
numbers.Clear();
xxxxxxxxxx
using System;
using System.Collections.Generic;
namespace main {
class Program {
private static void Main(string[] args) {
// syntax: List<type> name = new List<type>();
List<int> integerList = new List<int>();
for (int i = 0; i < 10; i++) {
// add item to list
integerList.Add(i);
}
for (int i = 0; i < 10; i++) {
// print list item
Console.WriteLine(integerList[i]);
}
}
}
}