By 19/12/2013 22 Comments

Iterate over a Collection Independently of Its Implementation in C# Example

What is Collection in C#

  • A collection is a set of similarly typed objects that are grouped together
  • The principal benefit of collections is that they standardize the way groups of objects are handled by your programs
  • Collections are data structures that holds data in different ways for flexible operations . C# Collection classes are defined as part of the System. Collections or System.Collections.Generic namespace
  • Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs
  • Collections provide a more flexible way to work with groups of objects. Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change. For some collections, you can assign a key to any object that you put into the collection so that you can quickly retrieve the object by using the key

Types of Collections

  1. Generic collections
  2. Non-Generic collections
  3. Specialized collections

Generic collections

  • The System.Collections.Generic namespace contains interfaces and classes that define generic collections
  • It allows users to create strongly typed collections

Non generic collections

  • They are defined in theSystem.Collections namespace
  • The non-generic collections are general purpose data structures that operate on object references. Thus, they can manage any type of object, but not in a type-safe manner
  • you can mix various types of data within the same collection

Following example describes how you can iterate over a collection in c#


int[] arrayInt = { 1, 2, 3, 4, 5 }; // initialize an array
foreach (int number in arrayInt)
{
Console.Write("{0} ", number); // loop through array's each element and print
}
Console.WriteLine(); // new line
List times = new List(
new DateTime[]{DateTime.Now, DateTime.UtcNow}); // create an list
foreach (DateTime time in times) // loop through each list and get time
{
Console.WriteLine(time); // print time
}
Dictionary<int, string=""> numbers = new Dictionary<int, string="">(); // declare dictionary generic collection 
numbers[1] = "One"; numbers[2] = "Two"; numbers[3] = "Three";
foreach (KeyValuePair<int, string=""> pair in numbers) // loop through each dictionary objects
{
Console.WriteLine("{0}", pair); // print 
}






Posted in: C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .