Thursday, May 27, 2021

C# Generic List and SortedList classes

Generic List class belongs to System.Collections.Generic namespace. The List collection is type-safe because it is generic and and each item added to List must belong to the type specified for List generic parameter type. List item has index value which is decided when the item is added to the List. In the following example, List generic collection initialization, its methods and properties are shown.



using System;

using System.Collections.Generic;

namespace ConsoleList

{
    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)

        {

            List voterlist = new List();

            voterlist.Add(1010101);
            voterlist.Add(1010121);
            voterlist.Add(1010131);
            voterlist.Add(1010151);
            voterlist.Add(1010191);
            voterlist.Add(1010221);

            List surnames = new List();

            surnames.Add("Gupta");
            surnames.Add("Sharma");
            surnames.Add("Verma");
            surnames.Add("Sethi");
            surnames.Add("Ambani");
            surnames.Add("kapoor");

            //Object Initializer

            Student s1 = new Student(){Id=1, Age=14, Name="Ajay"};
            Student s2 = new Student(){Id=2, Age=12, Name="Rajesh"};
            Student s3 = new Student(){Id=3, Age=13, Name="Amar"};
            Student s4 = new Student(){Id=4, Age=17, Name="Jyoti"};

            List students = new List();

            students.Add(s1);
            students.Add(s2);
            students.Add(s3);
            students.Add(s4);

            //display a list through foreach

            foreach (var item in voterlist)
            {
                Console.WriteLine("Voter Id: "+ item);
            }

            //display a list using index

            for (int i = 0; i < surnames.Count; i++)
            {
                Console.WriteLine(surnames[i]);
            }

            //display students details
            foreach (var student in students)
            {
                Console.Write(student.Id +" ");
                Console.Write(student.Name + " ");
                Console.Write(student.Age + " ");
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment

Hot Topics