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> ---")
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) ---")
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) ---")
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) ---")
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) ---")
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<> ---")
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 ---")
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>")
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
No comments:
Post a Comment