Basic What is List<T> Type in .NET
Arrays do not dynamically resize. The List type does. With List, you do not need to manage the size on your own. This type is ideal for linear collections not accessed by keys. It provides many methods and properties.
According to MSDN Documentation.. “Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists. “
Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)
Why do we need generic list?
First we have to understand that why we need generic list?
During development of a complex database driven applications, we need data manipulation in our business layer or database layer. For handling such type of manpulation we do use DataTable. But manipulaion of data in DataTable object, is having following problems.
- Problem in simple data manipulation (insert, update, delete) of conditioned rows.
- The chances of column mismatch is high.
- A lot of boxing and unboxing
- No type-safety
If we use List<T> type, we can easily ignore above hurdles in our development.
How to get List<T> type from Database?
If we use DataTable instead of List<T>, we easily picked up data in DataTable by one of the below methods.
-
objDataTable.Load(objCommand.ExecuteReader());
-
objDataAdapter.Fill(objDataset)
and several other ways...
For Getting data from database in List<T> type, we can use one of the following method.
- Using LINQ to SQL queries
- Using DataContext
- Converting DataTable into List<T> by using a custom conversion method.
All method are having its own pros and cons. Here we generally use DataContext.
Getting List<T> type from Database using DataContext
Syntax
DataContext dbContext = new DataContext("connectionString");
var resultList = dbContext.ExecuteQuery<T>("sql query").ToList();
Example:
First let us create a table in SQL
Create table Person
(
PersonID int primary key identity,
Name varchar(50),
Address varchar(100),
Salary decimal(19,2)
)Now let us create a class for holding Person data
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public decimal Salary { get; set; }
}
Finally create a function for getting Person List from Database
public List<Person> GetPersonList()
{
DataContext dbContext = new DataContext("myConnectionString");
using (dbContext)
{
var personList = dbContext.ExecuteQuery<Person>("Select * from Person").ToList();
}
return personList;
}
More about List<T> and LINQ Extension Methods

Join the conversation! Your thoughts help the community grow.