c# lists code example
Example 1: c# lists
// ------------------- How to initialize Lists? --------------------- //
using System.Collections.Generic // You need to include this!
// 1º Method
var myList = new List();
//OR
List myList = new List();
// 2º Method
List myList = new List() {2, 5, 9, 12};
// 3º Method
string myString = "Hello"
List myList = new List(myString); // Creates a list of characters from that string
//OR
var myFirstList = new List() {9, 2, 4, 3, 2, 1};
var mySecondList = new List(myFirstList); // Copy a list to a second list
// -------- How to dynamically change the List of elements? --------- //
// Use the Add or Insert method to add one element
myList.Add(4);
myList.Insert(0,3) // Insert element "3" in position "0"
// Use the AddRange method to add many elements (you can use an array or
// list, for passing the values)
myList.AddRange(new int[3] {3, 5, 5, 9, 2});
// Use the Remove method to eliminate specific elements
for (int i = 0; i < myList.Count; i++) // Use a for loop to remove
{ // repeated elements
if ( myList[i] == 5)
{
myList.Remove(myList[i]);
i--;
}
}
// Use the Clear method to remove all elements from the list
myList.Clear();
// ---------------- How to create a List of Lists? ------------------ //
List> myList = new List>(){
new List() {1,2,3},
new List() {4,5,6},
new List() {7,8,9}
};
Console.WriteLine(myList.ElementAt(0).ElementAt(1)); // You get "2"
Example 2: C# list
List myListOfStrings = new List
{
"this",
"is",
"my",
"list"
};
Example 3: make a list c#
IList newList = new List(){1,2,3,4};
Example 4: to list c#
var arr = new int[] {1, 2, 3};
List list = arr.ToList();