Difference between revisions of "List Csharp"
From Teknologisk videncenter
m (Created page with "=Example= <source lang=Csharp> using System; using System.Collections.Generic; List<int> numbers = new List<int>(); // Fill the List<int> by using the Add method foreach (int n...") |
m (added Category:Csharp using HotCat) |
||
Line 34: | Line 34: | ||
foreach (int number in numbers){ Console.WriteLine(number);} | foreach (int number in numbers){ Console.WriteLine(number);} | ||
</Source> | </Source> | ||
+ | |||
+ | [[Category:Csharp]] |
Revision as of 11:01, 19 January 2017
Example
using System;
using System.Collections.Generic;
List<int> numbers = new List<int>();
// Fill the List<int> by using the Add method
foreach (int number in new int[12]{10, 9, 8, 7, 7, 6, 5, 10, 4, 3, 2, 1})
{
numbers.Add(number);
}
// Insert an element in the penultimate position in the list, and move the last item up
// The first parameter is the position; the second parameter is the value being inserted
numbers.Insert(numbers.Count-1, 99);
// Remove the first element whose value is 7 (the 4th element, index 3)
numbers.Remove(7);
// Remove the element that's now the 7th element, index 6 (10)
numbers.RemoveAt(6);
// Iterate the remaining 11 elements using a for statement
Console.WriteLine("Iterating using a for statement:");
for (int i = 0; i < numbers.Count; i++)
{
int number = numbers[i]; // Note the use of array syntax
Console.WriteLine(number);
}
// Iterate the same 11 elements using a foreach statement
Console.WriteLine("\nIterating using a foreach statement:");
foreach (int number in numbers){ Console.WriteLine(number);}