DotNetCurry Logo

Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET

Posted by: Suprotim Agarwal , on 12/18/2008, in Category WinForms & WinRT
Views: 157061
Abstract: The List(T) represents a strongly typed collection of objects which is highly optimized for providing maximum performance and can be accessed using an index. This class provides methods to loop, filter, sort and manipulate collections.In this article we will see some common operations like search, sort, loop and manipulating lists.
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
 
The List(T) represents a strongly typed collection of objects which is highly optimized for providing maximum performance and can be accessed using an index. This class provides methods to loop, filter, sort and manipulate collections. For those interested, the non-generic version of this class is the ArrayList class.
In this article we will see some common operations like search, sort, loop and manipulating lists. Since this article focuses on demonstrating some common operations of the Generics List(T) class, I have decided to keep the sample as simple as possible and will go ahead with a console application. I assume you are familiar with the features of C# 2.0 and VB.NET and understand Generics in particular. If not, you can read some new features of 2.0 and 3.0 over here.
To create a console application, open Visual Studio 2005/2008 > File > New Project > Select your desired Language and in the template pane, select Console application.
I will be using a collection of a ‘Person’ class and store it in the List(T). To add a Person class to your application, right click your project > Add > Class > rename the class to Person.cs or Person.vb. Add the following properties to the Person class:
C#
using System;
using System.Collections.Generic;
using System.Text;
 
namespace CommonGenericOperations
{
    public class Person
    {
        public Person()
        {
 
        }
 
        public Person(int id, string first_name, string mid_name, string last_name, short age, char sex)
        {
            this.p_id = id;
            this.first_name = first_name;
            this.mid_name = mid_name;
            this.last_name = last_name;
            this.p_age = age;
            this.p_sex = sex;
        }
 
        private int p_id = -1;
        private string first_name = String.Empty;
        private string mid_name = String.Empty;
        private string last_name = String.Empty;
        private short p_age = 0;
        private char? p_sex = null;
 
 
        public int ID
        {
            get
            {
                return p_id;
            }
            set
            {
                p_id = value;
            }
        }
 
        public string FirstName
        {
            get
            {
                return first_name;
            }
            set
            {
                first_name = value;
            }
 
        }
 
        public string MiddleName
        {
            get
            {
                return mid_name;
            }
            set
            {
                mid_name = value;
            }
        }
 
        public string LastName
        {
            get
            {
                return last_name;
            }
            set
            {
                last_name = value;
            }
        }
 
        public short Age
        {
            get
            {
                return p_age;
            }
            set
            {
                p_age = value;
            }
        }
 
        public char? Sex
        {
            get
            {
                return p_sex;
            }
            set
            {
                p_sex = value;
            }
        }
    }  
}
 
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Text
 
 
Public Class Person
    Public Sub New()
 
    End Sub
 
    Public Sub New(ByVal id As Integer, ByVal first_name As String, ByVal mid_name As String, ByVal last_name As String, ByVal age As Short, ByVal sex As Char)
        Me.p_id = id
        Me.first_name = first_name
        Me.mid_name = mid_name
        Me.last_name = last_name
        Me.p_age = age
        Me.p_sex = sex
    End Sub
 
    Private p_id As Integer = -1
    Private first_name As String = String.Empty
    Private mid_name As String = String.Empty
    Private last_name As String = String.Empty
    Private p_age As Short = 0
    Private p_sex As Nullable(Of Char) = Nothing
 
    Public Property ID() As Integer
        Get
            Return p_id
        End Get
        Set(ByVal value As Integer)
            p_id = value
        End Set
    End Property
 
    Public Property FirstName() As String
        Get
            Return first_name
        End Get
        Set(ByVal value As String)
            first_name = value
        End Set
 
    End Property
 
    Public Property MiddleName() As String
        Get
            Return mid_name
        End Get
        Set(ByVal value As String)
            mid_name = value
        End Set
    End Property
 
    Public Property LastName() As String
        Get
            Return last_name
        End Get
        Set(ByVal value As String)
            last_name = value
        End Set
    End Property
 
    Public Property Age() As Short
        Get
            Return p_age
        End Get
        Set(ByVal value As Short)
            p_age = value
        End Set
    End Property
 
    Public Property Sex() As Nullable(Of Char)
        Get
            Return p_sex
        End Get
        Set(ByVal value As Nullable(Of Char))
            p_sex = value
        End Set
    End Property
End Class
Note: If you are using C# 3.0, you can use a new feature called ‘Automatic properties’        See how simple it is to create properties:
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MiddleName { get; set; }
        public int Age { get; set; }
        public char Sex { get; set; }
 
VB.NET does not support automatic properties.
Now go to the Program.cs or Module.vb and write the following code to add Person objects to the List(T) collection:
C#
        static void Main(string[] args)
        {
            List<Person> pList = new List<Person>();
            pList.Add(new Person(1, "John", "", "Shields", 29, 'M'));
            pList.Add(new Person(2, "Mary", "Matthew", "Jacobs", 35, 'F'));
            pList.Add(new Person(3, "Amber", "Carl", "Agar", 25, 'M'));
            pList.Add(new Person(4, "Kathy", "", "Berry", 21, 'F'));
            pList.Add(new Person(5, "Lena", "Ashco", "Bilton", 33, 'F'));
            pList.Add(new Person(6, "Susanne", "", "Buck", 45, 'F'));
            pList.Add(new Person(7, "Jim", "", "Brown", 38, 'M'));
            pList.Add(new Person(8, "Jane", "G", "Hooks", 32, 'F'));
            pList.Add(new Person(9, "Robert", "", "", 31, 'M'));
            pList.Add(new Person(10, "Cindy", "Preston", "Fox", 25, 'F'));
            pList.Add(new Person(11, "Gina", "", "Austin", 27, 'F'));
            pList.Add(new Person(12, "Joel", "David", "Benson", 33, 'M'));
            pList.Add(new Person(13, "George", "R", "Douglas", 55, 'M'));
            pList.Add(new Person(14, "Richard", "", "Banks", 22, 'M'));
            pList.Add(new Person(15, "Mary", "C", "Shaw", 39, 'F'));
        }
VB.NET
    Sub Main()
        Dim pList As List(Of Person) = New List(Of Person)()
        pList.Add(New Person(1, "John", "", "Shields", 29, "M"c))
        pList.Add(New Person(2, "Mary", "Matthew", "Jacobs", 35, "F"c))
        pList.Add(New Person(3, "Amber", "Carl", "Agar", 25, "M"c))
        pList.Add(New Person(4, "Kathy", "", "Berry", 21, "F"c))
        pList.Add(New Person(5, "Lena", "Ashco", "Bilton", 33, "F"c))
        pList.Add(New Person(6, "Susanne", "", "Buck", 45, "F"c))
        pList.Add(New Person(7, "Jim", "", "Brown", 38, "M"c))
        pList.Add(New Person(8, "Jane", "G", "Hooks", 32, "F"c))
        pList.Add(New Person(9, "Robert", "", "", 31, "M"c))
        pList.Add(New Person(10, "Cindy", "Preston", "Fox", 25, "F"c))
        pList.Add(New Person(11, "Gina", "", "Austin", 27, "F"c))
        pList.Add(New Person(12, "Joel", "David", "Benson", 33, "M"c))
        pList.Add(New Person(13, "George", "R", "Douglas", 55, "M"c))
        pList.Add(New Person(14, "Richard", "", "Banks", 22, "M"c))
        pList.Add(New Person(15, "Mary", "C", "Shaw", 39, "F"c))
    End Sub
I have also created a common method ‘PrintOnConsole’ that will help us print the List(T) on the console:
C#
        static void PrintOnConsole(List<Person> pList, string info)
        {
            Console.WriteLine(info);
            Console.WriteLine("\n{0,2} {1,7}    {2,8}      {3,8}      {4,2} {5,3}",
                "ID", "FName", "MName", "LName", "Age", "Sex");           
            pList.ForEach(delegate(Person per)
            {
                Console.WriteLine("{0,2} {1,7}    {2,8}      {3,8}      {4,2} {5,3}",
                    per.ID, per.FirstName, per.MiddleName, per.LastName, per.Age, per.Sex);
            });
 
            Console.ReadLine();
 
        }
VB.NET
   Sub PrintOnConsole(ByVal pList As List(Of Person), ByVal info As String)
        Console.WriteLine(info)
        Console.WriteLine(vbLf & "{0,2} {1,7} {2,8} {3,8} {4,2} {5,3}", "ID", "FName", "MName", "LName", "Age", _
        "Sex")
        For Each per As Person In pList
            Console.WriteLine("{0,2} {1,7} {2,8} {3,8} {4,2} {5,3}", per.ID, per.FirstName, per.MiddleName, per.LastName, per.Age, per.Sex)
        Next
        Console.ReadLine()
 
    End Sub
Note: VB.NET does not support anonymous methods.
With the base code set, let us see some common operations with the Generic List(T), in our case the List<Person> collection:
1. Looping through all items in the List(T)
C#
            PrintOnConsole(pList, "1. --- Looping through all items in the List<T> ---");
 
VB.NET
        PrintOnConsole(pList, "1. --- Looping through all items in the List<T> ---")
 
Generic 1
 
2. Filtering List(T) using a single condition - (Age > 35)
C#
            List<Person> filterOne = pList.FindAll(delegate(Person p) { return p.Age > 35; });
            PrintOnConsole(filterOne, "2. --- Filtering List<T> on single condition (Age > 35) ---");
 
VB.NET
        Dim filterOne As List(Of Person) = pList.FindAll(Function(p As Person) p.Age > 35)
        PrintOnConsole(filterOne, "2. --- Filtering List<T> on single condition (Age > 35) ---")
 
Generic 2
 
3. Filtering List(T) on multiple conditions (Age > 35 and Sex is Female)
C#
            List<Person> filterMultiple = pList.FindAll(delegate(Person p) { return p.Age > 35 && p.Sex == 'F'; });
            PrintOnConsole(filterMultiple, "3. --- Filtering List<T> on multiple conditions (Age > 35 and Sex is Female) ---");
 
VB.NET
        Dim filterMultiple As List(Of Person) = pList.FindAll(Function(p As Person) p.Age > 35 AndAlso p.Sex = "F"c)
        PrintOnConsole(filterMultiple, "3. --- Filtering List<T> on multiple conditions (Age > 35 and Sex is Female) ---")
 
 
Generic 3
 
4. Sorting List(T) (Sort on FirstName)
C#
            List<Person> sortFName = pList;
            sortFName.Sort(delegate(Person p1, Person p2)
            {
                return p1.FirstName.CompareTo(p2.FirstName);
            });
            PrintOnConsole(sortFName, "4. --- Sort List<T> (Sort on FirstName) ---");
 
VB.NET
        Dim sortFName As List(Of Person) = pList
        sortFName.Sort(Function(p1 As Person, p2 As Person) p1.FirstName.CompareTo(p2.FirstName))
        PrintOnConsole(sortFName, "4. --- Sort List<T> (Sort on FirstName) ---")
 
Generic 4
 
5. Sorting List(T) descending (Sort on LastName descending)
C#
List<Person> sortLNameDesc = pList;
            sortLNameDesc.Sort(delegate(Person p1, Person p2)
            {
                return p2.LastName.CompareTo(p1.LastName);
            });
            PrintOnConsole(sortLNameDesc, "5. --- Sort List<T> descending (Sort on LastName descending) ---");
 
VB.NET
        Dim sortLNameDesc As List(Of Person) = pList
        sortLNameDesc.Sort(Function(p1 As Person, p2 As Person) p2.LastName.CompareTo(p1.LastName))
        PrintOnConsole(sortLNameDesc, "5. --- Sort List<T> descending (Sort on LastName descending) ---")
 
Generic 5
 
6. Add new List(T) to existing List(T)
C#
List<Person> newList = new List<Person>();
            newList.Add(new Person(16, "Geoff", "", "Fisher", 29, 'M'));
            newList.Add(new Person(17, "Samantha", "Carl", "Baxer", 32, 'F'));
            pList.AddRange(newList);
            PrintOnConsole(pList, "6. --- Add new List<T> to existing List<> ---");
 
VB.NET
        Dim newList As List(Of Person) = New List(Of Person)()
        newList.Add(New Person(16, "Geoff", "", "Fisher", 29, "M"c))
        newList.Add(New Person(17, "Samantha", "Carl", "Baxer", 32, "F"c))
        pList.AddRange(newList)
        PrintOnConsole(pList, "6. --- Add new List<T> to existing List<> ---")
 
Generic 6
 
7. Remove multiple items from List(T) based on condition (remove male employees)
C#
List<Person> removeList = pList;
            removeList.RemoveAll(delegate(Person p) { return p.Sex == 'M'; });
            PrintOnConsole(removeList, "7. --- Remove multiple items from List<> based on condition ---");
 
VB.NET
        Dim removeList As List(Of Person) = pList
        removeList.RemoveAll(Function(p As Person) p.Sex = "M"c)
        PrintOnConsole(removeList, "7. --- Remove multiple items from List<> based on condition ---")
 
Generic 7
 
8. Create Read Only List(T)
C#
Console.WriteLine("8. --- Create Read Only List<> ---");
            IList<Person> personReadOnly = pList;
            Console.WriteLine("Before - Is List Read Only? True or False : " + personReadOnly.IsReadOnly);
            personReadOnly = pList.AsReadOnly();
            Console.WriteLine("After - Is List Read Only? True or False : " + personReadOnly.IsReadOnly);
            Console.ReadLine();
VB.NET
        Console.WriteLine("Create Read Only List<>")
        Dim personReadOnly As IList(Of Person) = pList
        Console.WriteLine("Before - Is List Read Only? True or False : " & personReadOnly.IsReadOnly)
        personReadOnly = pList.AsReadOnly()
        Console.WriteLine("After - Is List Read Only? True or False : " & personReadOnly.IsReadOnly & "</br>")
 
Generic 8
Well those were some common operations with the Generic Collection List(T). In the next article, I will demonstrate how to carry the same operations using the new features of C# 3.0 and VB.NET. I hope this article was useful and I thank you for viewing it. The entire source code of this article in C# and VB.NET can be dowloaded from here
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by papireddy on Friday, January 30, 2009 12:39 AM
very good
Comment posted by vuralpekyilmaz on Friday, July 10, 2009 4:48 PM
great:) thanks for everythink
Comment posted by vuralpekyilmaz on Friday, July 10, 2009 4:52 PM
great:) thanks for everythink
Comment posted by Suprotim Agarwal on Friday, July 17, 2009 2:48 AM
vuralpekyilmaz: You are welcome!
Comment posted by Sundar Rangharajan on Friday, April 16, 2010 6:04 AM
This is really a great example. I came here for something, ended up learing more. Keep up the good work :)
Comment posted by Johannes on Friday, September 17, 2010 4:38 AM
NICE! Finally i found i easy to understand on howto sort Generic Collections. I just used this line
"sortFName.Sort(Function(p1 As Person, p2 As Person) p1.FirstName.CompareTo(p2.FirstName))" and just like that I accomplished what I wanted. This instead of having to use an additional class to sort things for me.

Thanks!
Comment posted by Edward on Friday, September 24, 2010 1:45 AM
This is totally awesome! Thanks for your post.
Comment posted by Rajkumar on Thursday, February 3, 2011 9:16 AM
Hi
i am using VB.Net 2.0 window application. I am geeting a error the below line
Dim filterone As List(Of Person) = pList.FindAll(Function(p As Persion) p.Age > 35)
I am not familiar in generic collection list.
<--Function--> Expression expected.

Thanks
Comment posted by AndyT on Thursday, January 19, 2012 5:59 AM
Its great to see such a concise list of features in one place - plus you have supplied both VB and C# code.
Very easy to understand.
A nice post - thank you for taking the time.
Comment posted by Ravi Kumar.JG on Tuesday, January 24, 2012 4:57 AM
Awesome
Comment posted by marvin on Wednesday, February 22, 2012 2:10 AM
very nice thanks for this.
Comment posted by Jaypee Huda on Friday, June 21, 2013 3:32 AM
This is awesome!! Really helpful for me and developers. Thanks for sharing with us. Following links also helped me to

complete my task.

http://www.mindstick.com/Articles/ffc462a1-c822-4664-847a-3d05d80804ee/?Collections%20in%20C

http://msdn.microsoft.com/en-us/library/ybcx56wz(v=vs.80).aspx
Comment posted by Jaypee Huda on Friday, June 21, 2013 3:32 AM
This is awesome!! Really helpful for me and developers. Thanks for sharing with us. Following links also helped me to complete my task.

http://www.mindstick.com/Articles/ffc462a1-c822-4664-847a-3d05d80804ee/?Collections%20in%20C

http://msdn.microsoft.com/en-us/library/ybcx56wz(v=vs.80).aspx
Comment posted by Quite Code on Monday, October 21, 2013 1:59 PM
This is a great article on C# collections it motivated me to write my own you will find it at  <a href="http://www.quitecode.com/Collections/IntroCollections.htm">C# Collection comparison</a>
Comment posted by SimplyFred on Thursday, April 10, 2014 8:37 AM
This is really awesome. I am just diving into vs2013 and therefore some kind of a beginner. This tut made my day. Thanks
Comment posted by nigatu on Thursday, August 14, 2014 7:11 AM
it is very interesting code.