Introduction to Generic List using Csharp and ASP.NET
Introduction:
C# List is a collection class which can hold any type of data. Unlike Array, List provides capability to add items without specifying the size.
This article will cover the following topics:
- List- Add Item
- List- Delete Item
- List- Search
- List- Sort
- List- Display Data
- List- Other Functionality

Figure 1: Initial UI and List with Social Network Data
ASP.NET Script:
ASP.NET script is used to properly demonstrate the List functionality. The below script have the following items:
- ASP.NET TextBox Controls
- ASP.NET Label Controls and ListBox Control
- ASP.NET Buttons Controls
Listing 1: ASP.NET Script for List Demonstration
C# Code:
Lets start with C# code for List. First thing you have to do is add the
namespace for collection class.
Now create the object of List by
Now initialize the object by
The above initializations says that the List is type of , it means you can store the value type of string.
The below is some initial data, which will load on page_load event. The data is the name of some social network sites.
Listing 2: List- Initial Data
List- Add Item:
We have already seen that how to create and initialize the List object. Now will add some data into it. Use the Add() method to append the item in List.

Figure 2: Add Item - A item Added (“MySpace”)
Listing 3: List- Add Item Source Code
List- Delete Item:
There are two popular methods to remove the items from List - Remove() and RemoveAt(). The Remove method delete the data by value. However the RemoveAt delete the data by index.

Figure 3: Delete Item - (”Twitter”) is removed from List
Listing 4: List- Delete Item - Code
List- Search:
List class have a Contains() method to search particular item by value.
The below snippet shows the use of this method. Just pass the item into it and
it will return true in case of item found and false if no result found.

Figure 4: Search - The ‘Linkedin’ found in List
Listing 5: List- Search item - Code
List- Sort:
The List provide the Sort() method to sort All the data in it. This method sort the all item in ascending order. If you like to sort in descending order use the Reverse() method.

Figure 5: Sort- All the values are sorted now in ascending order
Listing 6: List- Sort data - Code
List- Display Data:
The below snippet is using foreach loop to add each item in ListBox.
Listing 7: List- Loop through items and display data on ASP page
List- Other Functionality:
Apart from above common operations, C# List provide some more common functions.
- Count: Returns the item count
- Clear(): Clear the items of List
- Capacity : Returns the capacity of List.
Listing 8: List- Other operation
Conclusion:
The above features are some most common one with c# list in next tutorial I will cover the other features of List. Please comment in case of any issues or suggestions.
No comments:
Post a Comment