How to Create a List of Item, with Multiple Fields: C#

If read more about DataTable, then follow How to Use DataTable in C#.

DataTable is the tabular form of data we are storing. Now to create a list, we have to create a list that can contains our desired set of data. List resides in System.Collection.Generic namespace of visual studio. Let suppose, we have a student class with some common properties like name, age, city, and date of birth.

To create a list, just create a list object type of student as in following line of c# code:
public class Student
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
public DateTime Dob { get; set; }

And the list object will create by the following line:

List<Student> stuList = new List<Student>();

This list can be used further like to insert new record of student, to bind this list with datagridview, to store temporary data from the database and many more. A list have many in-built functions, we have to just analyse them and use them.

This list is empty by default and can contains student type of data only. To insert some data in this list, we have to create a new object of student and then call the add() method of list. The add() method requires a parameter of student type. The syntax of method to add a new student is:
stuList.Add(new Student()
Name = "Jacob",
Age = 29,
City = "London",
Dob = new DateTime(1984, 5, 26)

This will add a single record of student with above details. We can add as many record as per our requirement.

In the next post we will use some in-built functions which requires Basics of LINQ language.


Post a Comment