Difference between revisions of "List Csharp"
From Teknologisk videncenter
m (added Category:Csharp using HotCat) |
m |
||
(3 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=Example= | =Example= | ||
− | <source lang= | + | <source lang=csharp> |
using System; | using System; | ||
using System.Collections.Generic; | using System.Collections.Generic; | ||
Line 33: | Line 33: | ||
Console.WriteLine("\nIterating using a foreach statement:"); | Console.WriteLine("\nIterating using a foreach statement:"); | ||
foreach (int number in numbers){ Console.WriteLine(number);} | foreach (int number in numbers){ Console.WriteLine(number);} | ||
− | </ | + | </source> |
[[Category:Csharp]] | [[Category:Csharp]] |
Latest revision as of 12:53, 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);}