Overview Of List Type In C#.NET

List Class : List is a member of System.Collection namespace in .NET which is having lots of features. 
Declaration: List is declared as follows. 
               List<int> list = new List<int>(); 
Description:
  1. List type in C# resizes itself if required hence you don’t need to worry for size of List.
  2. Used for Linear Collection which are not accessed by Keys.
  3. Lists are considered generics and constructed types.
  4. We must have to use <> (angle bracket) in the List declaration.
  5. It provides many attributes and methods to work with List type; some of them are described with example below. 
Memebers Of List class : Following are mainly used members of List Class.
(1)         Add() : This method is used to add primitive, objects /  references to the List object.
               List<int> list = new List<int>();
               list.Add(2);
               list.Add(3);
  • Adding objects/ references type to the List object.
class Program
{
    static void Main()
    {
               // Add three objects to a List.
               List<Test> list = new List<Test>();
               list.Add(new Test(1, 2));
               list.Add(new Test(3, 4));
               list.Add(new Test(5, 6));
    }
    class Test
    {
               int _a;
               int _b;
               public Test(int a, int b)
               {
                   _a = a;
                   _b = b;
               }
    }
}
(2)   AddRange(): This method adds entire collection of elements to the List object. It can replace tedious foreach loops that repeatedly call Add on List. We can pass any IEnumerable collection to AddRange, not just an array or another List.
class Program
{
    static void Main()
    {
               List<int> a = new List<int>();
               a.Add(1);
               a.Add(2);
               a.Add(5);
               a.Add(6);
               // Contains:
               // 1
               // 2
               // 5
               // 6
               int[] b = new int[3];
               b[0] = 7;
               b[1] = 6;
               b[2] = 7;
               a.AddRange(b);
               // Contains:
               // 1
               // 2
               // 5
               // 6
               // 7 [added]
               // 6 [added]
               // 7 [added]
               foreach (int i in a)
               {
                   Console.WriteLine(i);
               }
    }
}
Output
1
2
5
6
7
6
7
(3)   Count: Count Attribute is used toget the number of elements in your List. This is fast to access, if you avoid the Count() extension method. Count is equal to Length on arrays.
int elementCount = a.Count;
 
(4)   Clear(): Clear() method can be used to Clear all the element of the List object. Alternativelyyou can assign the List to null instead of calling Clear(), with similar performance. After assigning to null, you must call the constructor again.
class Program
{
    static void Main()
    {
               List<bool> list = new List<bool>();
               list.Add(true);
               list.Add(false);
               list.Add(true);
               Console.WriteLine(list.Count); // 3
               list.Clear();
               Console.WriteLine(list.Count); // 0
    }
}
Output
3
0
(5)   Copy array to List:  A list can also be created by an existing array. You can use the List constructor and pass it the array as the parameter. List receives this parameter, and fills its values from it.
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
               int[] arr = new int[3]; // New array with 3 elements
               arr[0] = 2;
               arr[1] = 3;
               arr[2] = 5;
               List<int> list = new List<int>(arr); // Copy to List
               Console.WriteLine(list.Count);       // 3 elements in List
    }
}
Output
3
(6)IndexOf()  : IndexOf() method returns the first occurrence of the element in the List collection.
    class Program
{
    static void Main()
    {
               List<int> primes = new List<int>(new int[] { 19, 23, 29 });
               int index = primes.IndexOf(23); // Exists in List
               Console.WriteLine(index);
    }
}
Output
1
 
(7)   Exist(): Checks whether an element is found in the List or not and return the corresponding Boolean value.
class Program
{
    static void Main()
    {
               List<int> list = new List<int>();
               list.Add(7);
               list.Add(11);
               list.Add(13);
               // See if any elements with values greater than 10 exist
               bool exists = list.Exists(element => element > 10);
               Console.WriteLine(exists);
               // Check for numbers less than 7
               exists = list.Exists(element => element < 7);
               Console.WriteLine(exists);
    }
}
Output
True
False
(8)   Contains():  It searches for a specific element to see if that element occurs at least once in the collection.
class Program
{
    static void Main()
    {
            // 1. Create List with three elements.
            var list = new List<string>();
            list.Add(“cat”);
            list.Add(“dog”);
            list.Add(“moth”);
            // 2. Search for this element.
            if (list.Contains(“dog”))
         {
                Console.WriteLine(“dog was found”);
            }
    }
}
Output
dog was found
 
(9)   Capacity: You can use the Capacity property on List, or pass an integer into the constructor, to improve allocation performance when using List. My research shows that capacity can improve performance by nearly two times for adding elements.
(10)  BinarySearch(): Optimizes searches on sorted collections. We evaluate the BinarySearch method on List and arrays. We may have a variable number of elements. Binary search is an amazing algorithm that hones in on values in sorted collections.

 

class Program
{
    static void Main()
    {
            List<string> l = new List<string>();
            l.Add(“acorn”);      // 0
            l.Add(“apple”);      // 1
            l.Add(“banana”);     // 2
            l.Add(“cantaloupe”); // 3
            l.Add(“lettuce”);    // 4
            l.Add(“onion”);      // 5
            l.Add(“peach”);      // 6
            l.Add(“pepper”);     // 7
            l.Add(“squash”);     // 8
            l.Add(“tangerine”);  // 9
            // This returns the index of “peach”.
            int i = l.BinarySearch(“peach”);
            Console.WriteLine(i);
            // This returns the index of “banana”.
            i = l.BinarySearch(“banana”);
            Console.WriteLine(i);
            // This returns the index of “apple”.
            i = l.BinarySearch(“apple”);
            Console.WriteLine(i);
    }
}
Output
6
2
1
 
 
(11) Join string List():  Here we see how you can use string. Join on a List of strings. This is useful when you need to turn several strings into one comma-delimited string. It requires the ToArray instance method on List.
class Program
{
    static void Main()
    {
               // List of cities we need to join
               List<string> cities = new List<string>();
               cities.Add(“New York”);
               cities.Add(“Mumbai”);
               cities.Add(“Berlin”);
               cities.Add(“Istanbul”);
               // Join strings into one CSV line
               string line = string.Join(“,”, cities.ToArray());
               Console.WriteLine(line);
    }
}
Output
New York,Mumbai,Berlin,Istanbul
(12) Keys in Dictionary:  List constructor can be used to get a List of keys in your Dictionary collection. This gives you a simple way to iterate over Dictionary keys or store them elsewhere. The Keys instance property accessor on Dictionary returns an enumerable collection of keys, which can be passed to the List constructor as a parameter.
class Program
{
    static void Main()
    {
               // Populate example Dictionary
               var dict = new Dictionary<int, bool>();
               dict.Add(3, true);
               dict.Add(5, false);
               // Get a List of all the Keys
               List<int> keys = new List<int>(dict.Keys);
               foreach (int key in keys)
               {
                   Console.WriteLine(key);
               }
    }
}
Output
3, 5
(13) Insert(): Insert() method can be used to insert an element into your List at any position.
class Program
{
    static void Main()
    {
           List<string> dogs = new List<string>(); // Example List
           dogs.Add(“spaniel”);         // Contains: spaniel
           dogs.Add(“beagle”);          // Contains: spaniel, beagle
dogs.Insert(1, “dalmation”); // Contains: spaniel, dalmation, beagle
           foreach (string dog in dogs) // Display for verification
           {
               Console.WriteLine(dog);
           }
    }
}
Output
spaniel
dalmation
beagle
(14) InsertRange(): This method places a collection of elements into a certain index of a List. The List resizes to accommodate the inserted elements. InsertRange handles collections that implement IEnumerable.
class Program
{
    static void Main()
    {
             List<int> a = new List<int>();
             a.Add(1);
             a.Add(2);
             a.Add(5);
             a.Add(6);
             // Contains:
             // 1
             // 2
             // 5
             // 6
             int[] b = new int[3];
             b[0] = 7;
             b[1] = 6;
             b[2] = 7;
             a.InsertRange(1, b);
             // Contains:
             // 1
             // 7 [inserted]
             // 6 [inserted]
             // 7 [inserted]
             // 2
             // 5
             // 6
             foreach (int i in a)
             {
                 Console.WriteLine(i);
             }
    }
}
Output
1
7
6
7
2
5
6
(15) Remove():  Eliminates elements from List. The target elements may be found at certain indexes; they may have certain values. They may instead match a condition we specify. The Remove method is effective for this.
class Program
{
    static void Main()
    {
             List<string> dogs = new List<string>();
             dogs.Add(“maltese”);    // Contains maltese
             dogs.Add(“otterhound”); // maltese, otterhound
             dogs.Add(“rottweiler”); // maltese, otterhound, rottweiler
             dogs.Add(“bulldog”);    // … rottweiler, bulldog
             dogs.Add(“whippet”);    // …. rottweiler, bulldog, whippet
             dogs.Remove(“bulldog”); // Remove bulldog
             foreach (string dog in dogs)
             {
                 Console.WriteLine(dog);
             }
             // Contains: maltese, otterhound, rottweiler, whippet
             dogs.RemoveAt(1); // Remove second dog
             foreach (string dog in dogs)
             {
                 Console.WriteLine(dog);
             }
             // Contains: maltese, rottweiler, whippet
    }
}
Output
maltese
otterhound
rottweiler
whippet
maltese
rottweiler
whippet
(16) RemoveAll ():  Filters and removes elements. It can be used with a lambda expression. This reduces the size of your code and improves its clarity. The List RemoveAll() method accepts a Predicate expression for this purpose.
class Program
{
    static void Main()
    {
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(2);
            list.Add(2);
            list.Add(4);
            list.Add(5);
            // Remove all list items with value of 2.
            // The lambda expression is the Predicate.
            list.RemoveAll(item => item == 2);
            // Display results.
            foreach (int i in list)
            {
                Console.WriteLine(i);
            }
    }
}
Output
1
4
5
(17)Sort(): A List can be sorted. The Sort method modifies the same List instance: it does not copy the List elements. Other methods too can sort a List—these include query expressions in the LINQ syntax. We further show how to sort List elements on a property of the element type.
class Program
{
    static void Main()
    {
            List<string> list = new List<string>();
            list.Add(“tuna”);
            list.Add(“velvetfish”);
            list.Add(“angler”);
            // Sort fish alphabetically, in ascending order (A – Z)
            list.Sort();
            foreach (string value in list)
            {
                Console.WriteLine(value);
            }
    }
}
Output
angler
tuna
velvetfish
(18) Convert List into DataTable: You want to display a List in your DataGridView. This can be done by converting the List to a DataTable first. With some custom List to DataTable conversion logic, you can get the best performance from the DataGridView by using the DataSource property.
 
               static DataTable ConvertListToDataTable(List<string[]> list)
               {
                   // New table.
                   DataTable table = new DataTable();
                   // Get max columns.
                   int columns = 0;
                   foreach (var array in list)
                   {
                               if (array.Length > columns)
                               {
                                   columns = array.Length;
                               }
                   }
                   // Add columns.
                   for (int i = 0; i < columns; i++)
                   {
                               table.Columns.Add();
                   }
                   // Add rows.
                   foreach (var array in list)
                   {
                               table.Rows.Add(array);
                   }
                   return table;
               }
// In the main class
                  List<string[]> list = new List<string[]>();
                   list.Add(new string[] { “Column 1”, “Column 2”, “Column 3” });
                   list.Add(new string[] { “Row 2”, “Row 2” });
                   list.Add(new string[] { “Row 3” });
                   // Convert to DataTable.
                  DataTable table = ConvertListToDataTable(list);
                   dataGridView1.DataSource = table;
(19) Reverse(): This example program uses Reverse on a List. The strings contained in the List are left unchanged. But the order they appear in the List is inverted. Afterwards we look inside the Reverse method.
class Program
{
    static void Main()
    {
            List<string> list = new List<string>();
            list.Add(“anchovy”);
            list.Add(“barracuda”);
            list.Add(“bass”);
            list.Add(“viperfish”);
            // Reverse List in-place, no new variables required
            list.Reverse();
            foreach (string value in list)
            {
                Console.WriteLine(value);
            }
    }
}
Output
viperfish
bass
barracuda
anchovy
(20) GetEnumerator():  Some collection types offer theGetEnumerator method. This method returns an Enumerator object that can be used to loop through the collection. Complete knowledge of the actual collection type is not needed. It becomes possible to write methods that act on the IEnumerator interface.
class Program
{
    static void Main()
    {
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(5);
            list.Add(9);
            List<int>.Enumerator e = list.GetEnumerator();
            Write(e);
    }
    static void Write(IEnumerator<int> e)
    {
            while (e.MoveNext())
            {
                int value = e.Current;
                Console.WriteLine(value);
            }
    }
}
Output
1
5
9
(21) Initialize List:  A List can be initialized in many ways. Each element can be added in a loop with the Add method. Alternatively a special initializer syntax form can be used. Objects inside the List can be initialized in this syntax form. Most syntax forms are compiled to the same intermediate representation.
class Program
{
    static void Main()
    {
            // Use collection initializer.
            List<string> list1 = new List<string>()
            {
                “carrot”,
                “fox”,
                “explorer”
            };
            // Use var keyword with collection initializer.
            var list2 = new List<string>()
            {
                “carrot”,
                “fox”,
                “explorer”
            };
            // Use new array as parameter.
            string[] array = { “carrot”, “fox”, “explorer” };
            List<string> list3 = new List<string>(array);
            // Use capacity in constructor and assign.
            List<string> list4 = new List<string>(3);
            list4.Add(null); // Add empty references. (BAD)
            list4.Add(null);
            list4.Add(null);
            list4[0] = “carrot”; // Assign those references.
            list4[1] = “fox”;
            list4[2] = “explorer”;
            // Use Add method for each element.
            List<string> list5 = new List<string>();
            list5.Add(“carrot”);
            list5.Add(“fox”);
            list5.Add(“explorer”);
            // Make sure they all have the same number of elements.
            Console.WriteLine(list1.Count);
            Console.WriteLine(list2.Count);
            Console.WriteLine(list3.Count);
            Console.WriteLine(list4.Count);
            Console.WriteLine(list5.Count);
    }
}
Output
3
3
3
3
3
(22)Remove Duplicates: Programs sometimes must removeduplicate List elements. There are many ways to remove these elements. Some are easier to implement than others. One approach uses the Distinct extension method.
class Program
{
    static void Main()
    {
            // List with duplicate elements.
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(2);
            list.Add(3);
            list.Add(3);
            list.Add(4);
            list.Add(4);
            list.Add(4);
            foreach (int value in list)
            {
                Console.WriteLine(“Before: {0}”, value);
            }
            // Get distinct elements and convert into a list again.
            List<int> distinct = list.Distinct().ToList();
            foreach (int value in distinct)
            {
                Console.WriteLine(“After: {0}”, value);
            }
    }
}
Output
Before: 1
Before: 2
Before: 3
Before: 3
Before: 4
Before: 4
Before: 4
After: 1
After: 2
After: 3

(23) Serialize List:  A List can be serialized to the disk. The problem is that you have a List of C# objects you want to write or serialize to a file. The next time your program runs, you want to get this List straight from the disk. We see a simple example of BinaryFormatter and its Serialize methods.

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable()]
public class Lizard
{
    public string Type { get; set; }     // String property for Lizard object
    public int Number { get; set; }      // Number of lizards
    public bool Healthy { get; set; }    // Whether lizard is healthy
    public Lizard(string t, int n, bool h)
    {
               Type =    t;
               Number =  n;
               Healthy = h;
    }
}
Example program
The second part of this tutorial is the Main method in your C# console program. It allows you to easily see how the data file is written to with BinaryFormatter, and how it is read from, deserialized.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
// [Note: You can paste the Lizard class here] <–
class Program
{
    static void Main()
    {
               while(true)
               {
                   Console.WriteLine(“s=serialize, r=read:”);
                   switch (Console.ReadLine())
                   {
                               case “s”:
                                   var lizards1 = new List<Lizard>();
                                   lizards1.Add(new Lizard(“Thorny devil”,                1, true));
                                   lizards1.Add(new Lizard(“Casquehead lizard”,           0, false));
                                   lizards1.Add(new Lizard(“Green iguana”,                4, true));
                                   lizards1.Add(new Lizard(“Blotched blue-tongue lizard”, 0, false));
                                   lizards1.Add(new Lizard(“Gila monster”,                1, false));
                                   try
                                   {
                                              using (Stream stream = File.Open(“data.bin”, FileMode.Create))
                                              {
                                                  BinaryFormatter bin = new BinaryFormatter();
                                                  bin.Serialize(stream, lizards1);
                                              }
                                   }
                                   catch (IOException)
                                   {
                                   }
                                   break;
                               case “r”:
                                   try
                                   {
                                              using (Stream stream = File.Open(“data.bin”, FileMode.Open))
                                              {
                                                  BinaryFormatter bin = new BinaryFormatter();
                                                  var lizards2 = (List<Lizard>)bin.Deserialize(stream);
                                                  foreach (Lizard lizard in lizards2)
                                                  {
                                                             Console.WriteLine(“{0}, {1}, {2}”,
                                                                  lizard.Type,
                                                                 lizard.Number,
                                                                 lizard.Healthy);
                                                  }
                                              }
                                   }
                                   catch (IOException)
                                   {
                                   }
                                   break;
                   }
               }
    }
}
Output
s=serialize, r=read:
s
s=serialize, r=read:
r
Thorny devil, 1, True
Casquehead lizard, 0, False
Green iguana, 4, True
Blotched blue-tongue lizard, 0, False
Gila monster, 1, False
s=serialize, r=read:
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s