Generic Collections - Some Common List (T) Operations
Generic Collections - Some Common List (T) Operations
NET
Page 1
Home .NET Tutorials Articles Write For Us About Contact jQuery-ASP.NET EBook .NET TOOLS Login/Subscribe
Google Custom Search
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: 83401
Tweet
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() {
LIKE US ON FACEBOOK
Make sure your internet connection is Check that the setup of any internet security If you are behind a firewall on a Local Try pressing the F 12 key on your keyboard Reload the page.
Need help?
Open the Opera Help. Go to Opera's online support desk.
Follow
3,967 followers
178
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
} 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 private private private private private int p_id = -1; string first_name = String.Empty; string mid_name = String.Empty; string last_name = String.Empty; short p_age = 0; char? p_sex = null;
Page 2
POPULAR ARTICLES
Making your existing ASP.NET MVC Web Site Mobile Friendly Twitter Bootstrap and ASP.NET MVC - Building a Responsive UI Installing and Configuring Microsoft SharePoint Server 2013 and SharePoint Farm on Windows Server 2008 R2 Layer Diagram in Visual Studio 2012 Image Retrieval using ASP.NET MVC 4.0 WebAPI
public int ID { get { return p_id; } set { p_id = value; } } public string FirstName { get { return first_name; } set { first_name = value; } }
with HttpResponseMessage Customizing ASP.NET Web API Routing for the User Defined methods in ApiController class Introducing Blend for Visual Studio 2012 Build a simple Windows 8 Store App Change Tracking and Committable databinding using KnockoutJS and ASP.NET Web API Coded UI Test Re-use and Customize the code generated with CUIT Builder using Visual Studio 2012 What's New in WCF 4.5 Deploying an ASP.NET Website to Azure in
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; }
Visual Studio 2012 from a Git Repository directly Lifecycle of an ASP.NET Web API Message SharePoint Server 2013 BI - Interactive Reports using Power View in Excel 2013 Testing and Consuming OData Services using Fiddler, LinqPad, Excel and SharePoint Using Facebook to Authenticate your ASP.NET MVC WebSite
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
set { p_age = value; } } public char? Sex { get { return p_sex; } set { p_sex = value; } } } }
Page 3
Name 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 Yes, I want to Subscribe! Char) Me.p_id = id Me.first_name = first_name Me.mid_name = mid_name LIST OF TUTORIALS Me.last_name = last_name Me.p_age = age Me.p_sex = sex ASP.NET Tutorials End Sub ASP.NET MVC & WebAPI Tutorials Private p_id As Integer = -1 WinRT & Windows 8 Apps Tutorials Private first_name As String = String.Empty SharePoint Tutorials Private mid_name As String = String.Empty Private last_name As String = String.Empty Visual Studio & TFS Tutorials Private p_age As Short = 0 WCF Tutorials Private p_sex As Nullable(Of Char) = Nothing jQuery & ASP.NET Tutorials Public Property ID() As Integer Windows Azure Tutorials Get WinForms Tutorials Return p_id End Get WPF Tutorials Set(ByVal value As Integer) LINQ Tutorials p_id = value Entity Framework End Set End Property C# Tutorials 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 .NET 3.5 Tutorials .NET 4.0 Tutorials Silverlight Tutorials ExpressionWeb Tutorials Windows Phone Tutorials
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
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 public public public public public int ID { get; set; } string FirstName { get; set; } string LastName { get; set; } string MiddleName { get; set; } int Age { get; set; } char Sex { get; set; }
Page 4
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))
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New pList.Add(New End Sub Person(2, "Mary", "Matthew", "Jacobs", 35, "F"c)) Person(3, "Amber", "Carl", "Agar", 25, "M"c)) Person(4, "Kathy", "", "Berry", 21, "F"c)) Person(5, "Lena", "Ashco", "Bilton", 33, "F"c)) Person(6, "Susanne", "", "Buck", 45, "F"c)) Person(7, "Jim", "", "Brown", 38, "M"c)) Person(8, "Jane", "G", "Hooks", 32, "F"c)) Person(9, "Robert", "", "", 31, "M"c)) Person(10, "Cindy", "Preston", "Fox", 25, "F"c)) Person(11, "Gina", "", "Austin", 27, "F"c)) Person(12, "Joel", "David", "Benson", 33, "M"c)) Person(13, "George", "R", "Douglas", 55, "M"c)) Person(14, "Richard", "", "Banks", 22, "M"c)) Person(15, "Mary", "C", "Shaw", 39, "F"c))
Page 5
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} {5,3}", "ID", "FName", "MName", "LName", "Age", "Sex"); pList.ForEach(delegate(Person per) { Console.WriteLine("{0,2} {1,7} {2,8} {3,8} {5,3}", per.ID, 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: per.FirstName, per.MiddleName, per.LastName,
{4,2}
{4,2}
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
Page 6
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) ---")
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 Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
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) ---");
Page 7
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) ---")
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) ---")
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
Page 8
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 ---")
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
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>")
Page 9
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
G iv e m e a + 1 if yo u think it w as a g oo d article . Th an ks !
RECOMMENDED ARTICLES Notifications and Background Tasks in Windows 8 Store Apps Integrating Share Charm in a Windows 8 Store Application Creating a Weather Gadget for Windows 7 Programmatically Increase, Decrease and Mute the Volume Suprotim is the founder and primary contributor Using .NET to Post a New BlogPost in Wordpress BING Desktop Translator using C# and VB.NET to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. Follow him on twitter @suprotimagarwal
Best ASP.NET Host of 2013
.NET 4.5, MVC, MS SQL, PHP5, MySQL5 Free Domain, 100% Uptime www.MochaHost.com/EasyASP
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
USER FEEDBACK 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 03, 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. POST YOUR COMMENT Name: E-mail: (Will not be displayed)
Page 10
Comment:
Insert Cancel
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM
Generic Collections - Some Common List(T) Operations using C# 2.0 and VB.NET
Page 11
POPULAR CATEGORIES ASP.NET ASP.NET MVC jQuery ASP.NET SharePoint VisualStudio & TFS
http://www.dotnetcurry.com/ShowArticle.aspx?ID=245
6/7/2013 12:03:56 PM