Showing posts with label Generic Collection. Show all posts
Showing posts with label Generic Collection. Show all posts

Sorted List - Generic

C# Sorted List

In c#, SortedList is a generic type of collection and it is used to store a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.

By default, the sortedlist will sort a key/value pairs in ascending order of the key and the sortedlist will allow storing only the strongly-typed objects i.e. the key/value pairs of the specified data type.

In c#, the sortedlist will allow us to store duplicate values but the keys must be unique and cannot be null to identify the values in sortedlist and the size of sortedlist will vary dynamically so you can add or remove elements from the sortedlist based on our application requirements.

C# includes two type of SortedList, generic SortedList and non-generic SortedList. Generic SortedList denotes with angel bracket: SortedList<TKey,TValue> where TKey is for type of key and TValue is for type of value. Non-generic type do not specify the type of key and values.


You can instantiate SortedList<TKey, TValue> by specifying type for key and value, as shown below.

Ex. SortedList<TKey, TValue> slist = new SortedList<TKey, TValue>();


Properties


 Property     Description
 Capacity     Gets or sets the number of elements that the SortedList<TKey,TValue> can store 
 Count Gets the total number of elements exists in the SortedList<TKey,TValue>.
 IsReadOnly Returns a boolean indicating whether the SortedList<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the SortedList<TKey,TValue>.
 Keys Get list of keys of SortedList<TKey,TValue>
 Values Get list of values in SortedList<TKey,TValue>.


Method

 Method         Description
Add  Add key-value pairs into SortedList<TKey, TValue>.
Remove Removes element with the specified key.
Remove At Removes element at the specified index.
Contains Key Checks whether the specified key exists in SortedList<TKey, TValue>.
Contains Value Checks whether the specified key exists in SortedList<TKey, TValue>.
Clear Removes all the elements from SortedList<TKey, TValue>.
Index Of Key Returns an index of specified key stored in internal array of SortedList<TKey, TValue>
Index Of Value
 Returns an index of specified value stored in internal array of SortedList<TKey,   TValue>
Try Get Value Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 class CollectionExamples
    {
        public static void Main(String[] args)
        {

            SortedList<int, string> sl = new SortedList<int, string>();
            sl.Add(3, "Three");
            sl.Add(1, "One");
            sl.Add(2, "Two");
            sl.Add(4, null);

            foreach (var item in sl.Keys)
            {
                Console.WriteLine("Sorted List {0}", item);
            }
            Console.ReadLine();

        }
    }


Dictionary

C# Dictionary


  • The Dictionary<TKey, TValue> class is a generic collection class in the System.Collection.Generics namespace. TKey denotes the type of key and TValue is the type of TValue.
  • There is a non-generic collection called a Hashtable, which does the same thing, except that it operates on type object. However, you want to avoid the non-generic collections and use their generic counterparts instead
  • Dictionary cannot include duplicate or null keys, where as values can be duplicated or set as null. Keys must be unique otherwise it will throw a runtime exception.
  • The capacity of a Dictionary is the number of elements that Dictionary can hold.


Properties

 Property

 Description

 Count             Gets the total number of elements exists in the Dictionary<TKey,TValue>              .
 IsReadOnly Returns a boolean indicating whether the Dictionary<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the Dictionary<TKey,TValue>.
 Keys Returns collection of keys of Dictionary<TKey,TValue>.
 Values Returns collection of values in Dictionary<TKey,TValue>.

Methods


 Method     Description
 Add                Add key-value pairs in Dictionary<TKey, TValue> collection.                                                                  
 Remove     Removes the first occurrence of specified item from the Dictionary<TKey, TValue>.
 ContainsKey  Checks whether the specified key exists in Dictionary<TKey, TValue>.
 ContainsValue Checks whether the specified key exists in Dictionary<TKey, TValue>.
 Clear Removes all the elements from Dictionary<TKey, TValue>.
 TryGetValue Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 public static void Main(String[] args)
   {
           
            Dictionary<int, string> _dictionary =  new Dictionary<int, string>();

            // Adding key/value pairs  
            _dictionary.Add(1, "Hello");
            _dictionary.Add(2, "This is");
            _dictionary.Add(3, "Blog for C#");

            _dictionary.Remove(1); //Remove value which key is 1

            Console.WriteLine("Is Key Exist?: {0}",_dictionary.ContainsKey(2));//Return True
            Console.WriteLine("Is Value Exist?: {0}", _dictionary.ContainsValue("This is"));//Return True
            foreach (KeyValuePair<int, string> ele1 in _dictionary)
            {
                Console.WriteLine("{0} and {1}",
                          ele1.Key, ele1.Value);
            }
            Console.ReadLine();

           
    }

List

 What is C# List<T>

  • List<T> class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace
  • List class can be used to create a collection of different types like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists.
  • It is different from the arrays. A List<T> can be resized dynamically but arrays cannot.
  • List<T> class can accept null as a valid value for reference types and it also allows duplicate elements.
  • If the Count becomes equals to Capacity, then the capacity of the List increased automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
  • List<T> class is the generic equivalent of ArrayList class by implementing the IList<T> generic interface.
  • This class can use both equality and ordering comparer.
  • List<T> class is not sorted by default and elements are accessed by zero-based index.
  • For very large List<T> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

Properties


 
Properties            
 Description 
 Capacity     Gets or sets the total number of elements the internal data structure can hold without resizing.
 Count Returns the total number of elements exists in the List<T>    
 Item Gets or sets the element at the specified index.


Methods


 Method     Usage    
 Add     Adds an element at the end of a List<T>.    
 AddRange     Adds elements of the specified collection at the end of a List<T>.        
 BinarySearch Search the element and returns an index of the element.
 Clear Removes all the elements from a List<T>.
 Contains Checks whether the speciied element exists or not in a List<T>
 Find Finds the first element based on the specified predicate function.
 ForEach Iterates through a List<T>.
 Remove<T>     Removes the first occurrence of a specific object from the List<T>.
 Remove All<T>            Removes all the elements that match the conditions defined by the specified predicate.
 Remove At(Int32) Removes the element at the specified index of the List<T>.
 RemoveRange(Int32,Int32)  Removes a range of elements from the List<T>.
 Reverse() Reverses the order of the elements in the List<T> or a portion of it.
 Sort()Sorts the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.    
 ToArray() Copies the elements of the List<T> to a new array.


Example:

class CollectionExamples
    {
        public static void Main(String[] args)
        {

            // Creating an List<T> of Integers 
            List<int> _List = new List<int>();

            // Adding elements to List 
            _List.Add(1);
            _List.Add(3);
            _List.Add(4);
            _List.Add(7);
            _List.Add(9);
            _List.Add(18);
            _List.Add(22);

            Console.WriteLine("Elements Present in List:\n");

            int p = 0;

            // Displaying the elements of List 
            foreach (int k in _List)
            {
                Console.Write("At Position {0}: ", p);
                Console.WriteLine(k);
                p++;
            }

            Console.WriteLine(" ");

            // removing the element at index 3 
            Console.WriteLine("Removing the element at index 3\n");
            _List.RemoveAt(4);

            int p1 = 0;

            // Displaying the elements of List 
            foreach (int n in _List)
            {
                Console.Write("At Position {0}: ", p1);
                Console.WriteLine(n);
                p1++;
            }
        }

Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...