What are generic collections in C#?

CsharpProgrammingServer Side Programming

Generic collections in C# include <List> , <SortedList> , etc.

List

List<T> is a generic collection and the ArrayList is a non-generic collection.

Let us see an example. Here, we have six elements in the list −

Example

 Live Demo

using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      // Initializing collections
      List myList = new List() {
         "one",
         "two",
         "three",
         "four",
         "five",
         "six"
      };
      Console.WriteLine(myList.Count);
   }
}

Output

6

SortedList

A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index.

Let us see an example. Here, we have four elements in the SortedList −

Example

 Live Demo

using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         SortedList sl = new SortedList();

         sl.Add("001", "Tim");
         sl.Add("002", "Steve");
         sl.Add("003", "Bill");
         sl.Add("004", "Tom");

         if (sl.ContainsValue("Bill")) {
            Console.WriteLine("This name is already in the list");
         } else {
            sl.Add("005", "James");
         }

         ICollection key = sl.Keys;

         foreach (string k in key) {
            Console.WriteLine(k + ": " + sl[k]);
         }
      }
   }
}

Output

This name is already in the list
001: Tim
002: Steve
003: Bill
004: Tom
raja
Published on 10-Aug-2018 10:54:25
Advertisements