Difference between revisions of "List Csharp"

From Teknologisk videncenter
Jump to: navigation, search
m (added Category:Csharp using HotCat)
m
Line 1: Line 1:
 
=Example=
 
=Example=
<source lang=Csharp>
+
<source lang=cli>
 
using System;
 
using System;
 
using System.Collections.Generic;
 
using System.Collections.Generic;
  
List<int> numbers = new List<int>();
+
Dictionary<string, int> ages = new Dictionary<string, int>();
  
// Fill the List<int> by using the Add method
+
// fill the Dictionary
foreach (int number in new int[12]{10, 9, 8, 7, 7, 6, 5, 10, 4, 3, 2, 1})
+
ages.Add("John", 51);    // using the Add method
{
+
ages.Add("Diana", 50);
    numbers.Add(number);
+
ages["James"] = 23;      // using array notation
}
+
ages["Francesca"] = 21;
 
 
// 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)
+
// iterate using a foreach statement
numbers.RemoveAt(6);
+
// the iterator generates a KeyValuePair item
 +
Console.WriteLine("The Dictionary contains:");
  
// Iterate the remaining 11 elements using a for statement
+
foreach (KeyValuePair<string, int> element in ages)
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
+
    string name = element.Key;
    Console.WriteLine(number);
+
    int age = element.Value;
 +
    Console.WriteLine($"Name: {name}, Age: {age}");
 
}
 
}
 
+
</source>
// Iterate the same 11 elements using a foreach statement
 
Console.WriteLine("\nIterating using a foreach statement:");
 
foreach (int number in numbers){    Console.WriteLine(number);}
 
</Source>
 
 
 
[[Category:Csharp]]
 

Revision as of 11:05, 19 January 2017

Example

using System;
using System.Collections.Generic;

Dictionary<string, int> ages = new Dictionary<string, int>();

// fill the Dictionary
ages.Add("John", 51);    // using the Add method
ages.Add("Diana", 50);
ages["James"] = 23;      // using array notation
ages["Francesca"] = 21;

// iterate using a foreach statement
// the iterator generates a KeyValuePair item
Console.WriteLine("The Dictionary contains:");

foreach (KeyValuePair<string, int> element in ages)
{
    string name = element.Key;
    int age = element.Value;
    Console.WriteLine($"Name: {name}, Age: {age}");
}