Demonstrate numerous things you can do with a List <T> collection class. - CSharp Collection

CSharp examples for Collection:List

Description

Demonstrate numerous things you can do with a List <T> collection class.

Demo Code

using System;/*w w  w.  j  a  v a 2s  . c  om*/
using System.Collections.Generic;
using System.Collections;   // For old-style ArrayList.
class Program
{
   static void Main(string[] args)
   {
      List<string> nameList = new List<string>();
      nameList.Add("one");
      List<object> objects = new List<object>();
      ArrayList oldObjects = new ArrayList();
      List<int> intList = new List<int>();
      intList.Add(3);                          // Fine.
      intList.Add(4);
      Console.WriteLine("Printing intList:");
      foreach (int i in intList)  // foreach just works for all collections.
      {
         Console.WriteLine("int i = " + i);
      }
      List<Student> studentList = new List<Student>();
      Student student1 = new Student("Q");
      Student student2 = new Student("F");
      studentList.Add(student1);
      studentList.Add(student2);
      Student[] students = { new Student("Mox"), new Student("Fox") };
      studentList.AddRange(students); // Add whole array to List.
      Console.WriteLine("Num students in studentList = " + studentList.Count);
      Student[] studentsFromList = studentList.ToArray();
      // Search with IndexOf().
      Console.WriteLine("Student2 at " + studentList.IndexOf(student2));
      string name = studentList[3].Name;  // Access list by index.
      if (studentList.Contains(student1))  // Search with Contains().
      {
         Console.WriteLine(student1.Name + " contained in list");
      }
      studentList.Sort(); // Assumes Student implements IComparable interface (Ch 14).
      studentList.Insert(3, new Student("Ross"));
      studentList.RemoveAt(3);  // Deletes the third element.
      Console.WriteLine("removed {0}", name);         // Name defined above.
      Student[] moreStudents = studentList.ToArray(); // Convert list to array.
   }
}
class Student : IComparable
{
   private string _name;
   public Student(string name)
   {
      this._name = name;
   }
   public string Name
   {
      get { return _name; }
   }
   public int CompareTo(object rightObject)
   {
      Student leftStudent = this;
      if (!(rightObject is Student))
      {
         Console.WriteLine("Compare method passed a nonStudent");
         return 0;
      }
      Student rightStudent = (Student)rightObject;
      if (string.Compare(rightStudent.Name, leftStudent.Name) < 0)
      {
         return -1;
      }
      if (string.Compare(rightStudent.Name, leftStudent.Name) > 0)
      {
         return 1;
      }
      return 0;
   }
}

Result


Related Tutorials