List T - C Tutorial For Beginners - CodeProject
List T - C Tutorial For Beginners - CodeProject
articles Q&A forums stuff lounge ? Search for articles, questions, tip
A C# tutorial of List for beginners. The demo is carried out in ASP.NET WebForms.
Introduction
This article is about an introduction of C# List<T> and is demonstrated in ASP.NET
WebForms.
Before Start
Creates a new project of ASP.NET WebForms, which commonly refers to the project type of
ASP.NET Web Application (.NET Framework) in Visual Studio.
Here is a YouTube video guide for installing Visual Studio and creating new project of
ASP.NET WebForms:
Let's creates a new page. Here’s an example of initial ASP.NET front page code:
ASP.NET
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
ASP.NET
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<pre><asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>
</pre>
</form>
</body>
</html>
Go to code behind:
Here’s the initial code behind of a new page. The C# code demonstrated in the rest of this
article will be placed within the main method of Page_Load.
C#
}
}
string object
int object
decimal object
DateTime object
any class object
etc.
C#
C#
C#
lst.Count
Foreach loop
For loop
C#
Or you can also use the keyword “var” as a generic declaration of implicitly typed local
variable, for example:
C#
C# Shrink ▲
ph1.Controls.Add(new LiteralControl(sb.ToString()));
Note:
The string can also be combined by using string operation of “+=”. For example:
C#
Note:
This will also produce the same output, but however, if you are running this in large
amount of loops, using the string operation of “+=” will cause a lots of memory
usage. String object is immutable. An immutable object is an object that cannot be
changed after it has been created. Every time a text is trying to append to it, a new
string object is created in memory. This will create a lots of strings in memory.
StringBuilder object does not has this problem. It is a specialized string handling
object that can be altered and expanded on the go.
C#
int i = 0;
C#
i < lst.Count;
C#
i++
Loop from the first data in the List<T>:
C# Shrink ▲
ph1.Controls.Add(new LiteralControl(sb.ToString()));
Press [F5] or run the website, and this will produce the following output:
C#
Output:
Total objects in List: 7
====================================
Loop 6: green
Loop 5: forest
Loop 4: enter
Loop 3: part
Loop 2: car
Loop 1: hello
Loop 0: book
C#
C#
Let’s do a simple HTML form to play around. Go to the ASP.NET front page, insert the
following HTML & controls:
ASP.NET Shrink ▲
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
Enter a number:
<asp:TextBox ID="txtNumber"
runat="server" Width="80px"></asp:TextBox>
<br />
<br />
<asp:Button ID="btGetValue" runat="server"
Text="Get Value" OnClick="btGetValue_Click" />
<br />
<br />
Output:
<hr />
<pre><asp:PlaceHolder ID="ph1"
runat="server"></asp:PlaceHolder></pre>
</form>
</body>
</html>
Go to code behind, the initial code behind will look something like this:
C#
}
}
C#
}
catch (Exception ex)
{
}
}
Before we continue, let's explains what is the usage of "try" and "catch" block code.
The block of "try" and "catch" are used to capture errors that might occur during real-time
operation.
If there is any error occurs in the “try” block, the operation will stop and falls down to the
“catch” block. An Exception will be produced (An exception is raised).
The Exception contains the information/description of what kind of error that has been
generated. It gives you a clue of how the error is generated.
Let’s try to make an error to see the effect.
C#
try
{
string aa = "hello";
}
catch (Exception ex)
{
string err_message = ex.Message;
ph1.Controls.Add(new LiteralControl(err_message));
}
C#
try
{
string aa = "hello";
int num = Convert.ToInt32(a);
}
catch (Exception ex)
{
string err_message = ex.Message;
ph1.Controls.Add(new LiteralControl(err_message));
}
C#
try
{
string aa = "hello";
int num = Convert.ToInt32(a);
string output = num.ToString();
ph1.Controls.Add(new LiteralControl(output));
}
catch (Exception ex)
{
string err_message = ex.Message;
ph1.Controls.Add(new LiteralControl(err_message));
}
string aa is a text and it’s not a numeric characters. Therefore, it can’t be converted into
number and this will cause an error. Press [F5] to run the code and the following output will
produce:
Input string was not in a correct format.
C#
try
{
string aa = "123";
int num = Convert.ToInt32(a);
string output = num.ToString();
ph1.Controls.Add(new LiteralControl(output));
}
catch (Exception ex)
{
string err_message = ex.Message;
ph1.Controls.Add(new LiteralControl(err_message));
}
123
C#
try
{
}
catch (Exception ex)
{
string err_message = ex.Message;
ph1.Controls.Add(new LiteralControl(err_message));
}
Now, we’ll going to capture the input value from the form submission. The form is considered
“submitted” when the user click on the button “btGetValue” which displayed as “Get Value”
at user’s web browser.
C#
try
{
string input = Request.Form["txtNumber"] + "";
}
catch (Exception ex)
{
string err_message = ex.Message;
ph1.Controls.Add(new LiteralControl(err_message));
}
C#
try
{
string input = Request.Form["txtNumber"] + "";
int num = Convert.ToInt32(input);
}
catch (Exception ex)
{
string err_message = ex.Message;
ph1.Controls.Add(new LiteralControl(err_message));
}
As you can see, the value supplies by user is stored in the form input of "txtNumber" (the
textbox). If the user enters non-numeric characters, this will cause the program to encouter
error (raise Exception) and crash.
That's why a "try" & "catch" block is used to prevent the program from crashing and let the
program keeps running.
Get the value from the string and displays it to front end:
C#
try
{
string input = Request.Form["txtNumber"] + "";
int num = Convert.ToInt32(input);
string output = lst[num];
ph1.Controls.Add(new LiteralControl(output));
}
catch (Exception ex)
{
string err_message = ex.Message;
ph1.Controls.Add(new LiteralControl(err_message));
}
Press [F5] and run the website.
Instead of using “try” & “catch“, use int.TryParse() to test and convert the user input
value.
C# Shrink ▲
ph1.Controls.Add(new LiteralControl(output));
C# Shrink ▲
sb.AppendLine("===============");
sb.AppendLine("Before");
sb.AppendLine("===============");
int count = 0;
lst[0] = "apple";
lst[1] = "orange";
lst[2] = "grape";
lst[3] = "watermelon";
lst[4] = "lemon";
lst[5] = "banana";
lst[6] = "strawberry";
sb.AppendLine();
sb.AppendLine("===============");
sb.AppendLine("After");
sb.AppendLine("===============");
count = 0;
ph1.Controls.Add(new LiteralControl(sb.ToString()));
Output:
===============
Before
===============
Item 1: book
Item 2: hello
Item 3: car
Item 4: part
Item 5: enter
Item 6: forest
Item 7: green
===============
After
===============
Item 1: apple
Item 2: orange
Item 3: grape
Item 4: watermelon
Item 5: lemon
Item 6: banana
Item 7: strawberry
C#
List.Insert(position, value);
The first parameter will be the position of new item that will be inserted.
C#
lst.Insert(0, "house");
C#
lst.Insert(2, "house");
C#
lst.Remove(0);
C#
lst.Remove(3);
C#
lst.Remove("car");
if (lst.Contains("book"))
{
sb.AppendLine("Yes, book exists");
}
else
{
sb.AppendLine("No, book is not existed")l
}
C#
int total = 0;
ph1.Controls.Add(new LiteralControl(output));
Output:
1743
C#
ph1.Controls.Add(new LiteralControl(output));
Output:
8320.886
C#
class Member
{
public string Name { get; set; }
public string Tel { get; set; }
public string Location { get; set; }
}
Declaring List of Member Object and display the name by using Foreach Loop:
C# Shrink ▲
int count = 0;
ph1.Controls.Add(new LiteralControl(sb.ToString()));
Output:
Let’s build a “Get Members” form that display the HTML table of Members’ Details. Build the
ASP.NET front page as follows:
ASP.NET Shrink ▲
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
table {
border-collapse: collapse;
}
th {
padding: 10px;
color: white;
background: #646464;
border-right: 1px solid #a7a7a7;
}
td {
border: 1px solid #a8a8a8;
padding: 10px;
}
tr:nth-child(odd){
background: #e6e6e6;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<hr />
</form>
</body>
</html>
C# Shrink ▲
sb.Append($@"
Total Members: {lst.Count}
<table>
<tr>
<th>No</th>
<th>Member's Name</th>
<th>Tel</th>
<th>Location</th>
</tr>
");
int count = 0;
sb.Append("</table>");
ph1.Controls.Add(new LiteralControl(sb.ToString()));
}
The output:
Sorting List<T> (Rearrange the List in Specific Orders)
This article will introduce two methods:
C#
C#
// manually compare
lst.Sort((x, y) => x.Name.CompareTo(y.Name));
// using delegate
lst.Sort(delegate (Member x, Member y) {
return x.Name.CompareTo(y.Name);
});
C#
// using delegate
lst.Sort(delegate (Member x, Member y) {
return y.Name.CompareTo(x.Name);
});
Sort by two elements, i.e., Name and Location (both ascending order):
C#
OrderBy()
OrderByDescending()
ThenBy()
ThenByDescending()
Sort by one element, i.e., Name (ascending order):
C#
C#
Sort by two elements, i.e., Name and Location (both ascending order):
C#
History
16th December, 2022: Initial version
This article was originally posted at https://adriancs.com/c-sharp/491/c-tutorial-list
License
This article, along with any associated source code and files, is licensed under The Code
Project Open License (CPOL)
Written By
adriancs
Software Developer
Other Other
Programming is an art.
Search Comments
My vote of 2
tbayart 20-Dec-22 8:29
Refresh 1