This is third part of the 'LINQ' series articles that I have started from here. In this article, you will learn something about "Generic" collections such as what they are and why we need them in LINQ.


First of all let's understand what "Arrays" are, what ".NET Collections" are and what ".NET Generic Collections" are. You will see the following advantages and disadvantages in the examples given below.

Collection Types Advantages Disadvantages
Arrays Strongly Typed (Type Safe)
  • Zero Index Based
  • Cannot grow in size once initialized

.NET Collections (like ArrayList, Hashtable etc)
  • Can grow in size
  • Convenient to work with Add, Remove

Not Strongly Typed
.NET Generic Collections (like List<T>, GenericList<T> etc)
  • Type Safe like arrays
  • Can grow automatically like ArrayList
  • Convenient to work with Add, Remove


Now, let's discuss each of the collection types given in the above table to feel the real pain of development.


Array

array.jpg


If you use array:

ArrayList (System.Collection)

arraylist.jpg


If you use ArrayList:

List<T> (System.Collection.Generic)

listgeneric.png


Now, in short we can say, a list has both the features that we have in arrays and arraylists.


Why we need List (which is generic type) in LINQ?


LINQ queries are based on generic types, which were introduced in version 2.0 of the .NET Framework. LINQ queries return collections and we don't even know what type of data we will get from the database and that is the reason we use a generic type like List<T>, IEnumerable<T>, IQueryable<T> etc. For example:

list-in-linq.jpg


In the above example, we have used the IEnumerable<T> interface and a LINQ query and then by using a foreach loop I'm able to get my data.


One more example:

IEnumerable<Customer> customerQuery =

from cust in customers

where cust.City == "Bokaro"

select cust;


foreach (Customer customer in customerQuery)

{

Console.WriteLine(customer.LastName + " = " + customer.Age);

}


In the above example you can see, using a LINQ query I'm not only limited to select the string value that is LastName, I'm also able to select an integer value that is Age.


So, this could be the great example of generic classes.


Here is some counterpart of Generic Collections over non-generic collections:

Collections

(System.Collection)

Generic Collection

(System.Collection.Generic)

ArrayList List<T>
Hasgtable Dictionary<Tkey, Tvalue>
Stack Stack<T>
Queue Queue<T>


I hope you will find it useful. Thanks for reading.