A Basic Understanding of Generic List

 

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

  1. Constructor

    List<T>()

    Initializes a new instance of the List<T> class that is empty and has the default initial capacity.

    Example :
     

     var list = new List<T>();
     

  2. Methods

    1. Add()

      Adds an object to the end of the List<T>.

      Example
       

      //Adding Item in List

      objPersonList.Add(new Person() { Name = "Mayank", Address = "Jogeshwari" });
       

    2. Any()

      Any receives a Predicate. It determines if any element in a collection matches a certain condition. You could do this imperatively, using a loop construct. But the Any extension method provides another way. It reduces code size.

      Example:
       

      //returns true if objPersonList contains element(s)

      objPersonList.Any();
       

    3. Average()

      Average is an extension method. It computes the average value using only one statement. It provides a declarative way to compute the average value of a sequence in the C# language.

      Example:
       

      //Get the Average value of passed function delegate

      decimal averageSal = objPersonList.Average(Obj => Obj.Salary);
       

    4. Clear()

      Removes all elements from the List<T>.

      Example:
       

      //clears the contents of the list
       objPersonList.Clear();
       

    5. Contains()

      Determines whether an element is in the List<T>.

      Example:
       

      //returns true if the Person object is the element of list

      objPersonList.Contains(new Person());
       

    6. Count()

      Gets the number of elements actually contained in the List<T>.

      Example:
       

      //get the total element count in the list

      int totalPerson = objPersonList.Count;

      //get the total element count in the list

      //with the given condition(s)

      int totalPersonsKandivali = objPersonList.Count(Obj => Obj.Address == "Kandivali");
       

    7. DefaultIfEmpty()

      DefaultIfEmpty handles empty collections in a special way. It returns a default value, not an error. With it, we replace empty collections with a singleton collection that may be more compatible with other parts of the C# program.

      Example:
       

      //Set and returns the Default value of the list is empty

      objPersonList.DefaultIfEmpty(new Person());
       

    8. ElementAt()

      ElementAt gets an element at an index. In many IEnumerable types, you cannot directly index a certain element. Instead of using a foreach-loop or other techniques, we can use the ElementAt method from System.Linq.

      Example:
       

      //get the element at specified position

      Person firstPerson = objPersonList.ElementAt(1);
       

    9. Exists()

      Determines whether the List<T> contains elements that match the conditions defined by the specified predicate.

      Example:
       

      //returns true if the any element exists

      //with specified condition

      objPersonList.Exists(Obj => Obj.Name == "Sachin");
       

    10. Find()

      Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

      Example:
       

      //returns the "first" element from the list

      //with the specified condition

      //Note: 1. returns null if no element is found

      //Note: 2. changes in resultant element is also

      // affects the original list element

      objPersonList.Find(Obj => Obj.Address == "Andheri");
       

    11. FindAll()

      Retrieves all the elements that match the conditions defined by the specified predicate.

      Example:
       

      //returns the "all" element from the list

      //with the specified condition

      //Note: 1. returns null if no element is found

      //Note: 2. changes in resultant element is also

      // affects the original list element

      objPersonList.FindAll(Obj => Obj.Address == "Andheri");
       

    12. FindIndex()

      Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire List<T>.

      Example:
       

      //finds the element index with given condition

      int indexOfRavindra = objPersonList.FindIndex(Obj => Obj.Name == "Ravindra");
       

    13. FindLast()

      Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire List<T>.

      Example:
       

      //returns the "Last" element from the list

      //with the specified condition

      //Note: 1. returns null if no element is found

      //Note: 2. changes in resultant element is also

      // affects the original list element

      objPersonList.FindLast(Obj => Obj.Address == "Andheri"); 
       

    14. First()

      First locates the first matching object. These objects can be of any type. We access the First extension method in the System.Linq namespace. The argument to First is a Predicate instance.

      Example:
       

      //returns the "First" element from the list

      //Note: 1. returns null if no element is found

      //Note: 2. changes in resultant element is also

      // affects the original list element

      objPersonList.First();
       

    15. ForEach()

      Performs the specified action on each element of the List<T>.

      Example 1:
       

      //Iterate through list elements

      objPersonList.ForEach(Obj => Obj.Address += ", City=Mumbai");

      Example 2:

      //Iterate through list elements (multiline)

      objPersonList.ForEach(Obj =>

      {

      Obj.Address += ", State=Maharashtra";

      });
       

    16. IndexOf()

      Searches for the specified object and returns the zero-based index of the first occurrence within the entire List<T>.

      Example:
       

      //get the index of specified person

      int indexOf = objPersonList.IndexOf(new Person());
       

    17. Insert()

      Inserts an element into the List<T> at the specified index.

      Example:
       

      //Insert an element at specified index

      objPersonList.Insert(3new Person() { Name = "Sushil", Address = "Mira Road" });
       

    18. Last()

      The last element is sometimes the most important one. With the Last extension method, you can get it with a single method call in your C# program. This simplifies some program logic.

      Example:
       

      //returns the "Last" element from the list

      //Note: 1. returns null if no element is found

      //Note: 2. changes in resultant element is also

      // affects the original list element

      objPersonList.Last();
       

    19. Max()

      Max looks through the source collection and returns the largest value.

      Example:
       

      //Get the Max value of passed function delegate

      decimal maxSal = objPersonList.Max(Obj => Obj.Salary);
       

    20. Min()

      Min looks through the source collection and returns the smallest value.

      Example:
       

      //Get the Min value of passed function delegate

      decimal minSal = objPersonList.Min(Obj => Obj.Salary);
       

    21. Remove()

      Removes the first occurrence of a specific object from the List<T>.

      Example:
       

      //removes an specified element from the list

      objPersonList.Remove(new Person());
       

    22. RemoveAll()

      Removes all the elements that match the conditions defined by the specified predicate.

      Example:
       

      //removes all elements from the list with specified condition(s)

      objPersonList.RemoveAll(Obj => Obj.Address == "Jogeshwari");
       

    23. RemoveAt()

      Removes the element at the specified index of the List<T>.

      Example:
       

      //removes the element from the specified index

      objPersonList.RemoveAt(2);
       

    24. Reverse()

      Reverses the order of the elements in the entire List<T>.

      Example:
       

      //Reverse the list

      objPersonList.Reverse();
       

    25. Select()

      The name "select" is possibly confusing, as the method actually provides a mutation function, not just a selection function.

      Example:
       

      //returns IEnumrable<bool> type which matches the condition

      objPersonList.Select(Obj => Obj.Address == "Andheri, City=Mumbai, State=Maharashtra").ToList();
       

    26. Single()

      Single searches for single instances. It is found in System.Linq. With it, we search a collection for a single instance of an element matching a condition. If the collection has any number other than one element, we get an exception.

      Example:
       

      //returns the only single element with specified condition

      //Note: it throws an exception if resultant elements

      // are more than one than one.

      objPersonList.Single(Obj => Obj.Name == "Sachin");
       

    27. Skip()

      Skip is an extension method. It returns only the elements following a certain number of initial elements that must be ignored. It is found in the System.Linq namespace.

      Example:
       

      //return elements skipping specified no of elements

      objPersonList.Skip(3);
       

    28. SkipWhile()

      SkipWhile skips over elements matching a condition. This method is provided in the System.Linq namespace for the C# language.

      Example:
       

      //return elements skipping while the specified condition matched

      objPersonList.SkipWhile(Obj => Obj.Name == "Sachin");
       

    29. Sum()

      Sum totals values in an array. It computes the sum total of all the numbers in an array, or List, of integers. This extension method in LINQ provides an excellent way to do this with minimal calling code

      Example:
       

      //Get the Sum value of passed function delegate

      decimal totalSal = objPersonList.Sum(Obj => Obj.Salary);
       

    30. Take()

      Take returns the first specified number of elements. It acts upon an IEnumerable sequence. It returns another IEnumerable sequence containing the specified elements.

      Example:
       

      //return elements taking specified no of elements

      objPersonList.Take(3);
       

    31. TakeWhile()

      TakeWhile returns elements while a Predicate matches. The Predicate returns true or false. When it returns false, TakeWhile returns. TakeWhile operates from the beginning of an IEnumerable collection.

      Example:
       

      //return elements taking while the specified condition matched

      objPersonList.TakeWhile(Obj => Obj.Name == "Sachin");
       

    32. Where()

      Where filters elements from a collection.

      Example:
       

      //returns the "all" element from the list

      //with the specified condition

      //Note: 1. returns blank if no element is found

      //Note: 2. returns type is IEnumrable<T> type

      //Note: 3. changes in resultant element is

      // affects the original list element

      objPersonList.Where(Obj => Obj.Address == "Andheri, City=Mumbai, State=Maharashtra");

 

Up Next
    Ebook Download
    View all
    Learn
    View all