explore.net

08/Feb/2015

List vs IEnumerable vs IQueryable vs ICollection vs IDictionary

Filed under: C#.NET — NisanthVijay @ 6:28 am

This article shows comparision about data structure, Array, ArrayList, List, IList, ICollection, Stack, Queue, HashTable, Dictionary, IQueryable, IEnumerable.
 Complete Collection Comparison

Collection

Collection is set of related records. It includes a meaningful unit:
We should select appropriate container to store data  temporarily for fetch and modification process.
Appropriate container depends on:
1. Our aim which we want to do on data ( just reading, doing modification such as insert, delete, update )
2. Number of records which should be transferred

Array

1. Fixed Length -> Its size is not flexible. It is determined at instantiation time.

2. Strongly Typed -> Developers determine its type at the instantiation time instead of runtime. This feature makes to run fast at runtime, since it does not need to wait for type definition.

3. Developers use “foreach” keyword to fill and iterate through array.

Fixed Length and Strongly Typed consume less memory, therefore it has good performance.

img1

ArrayList

1. Arraylist is NOT Fixed Length -> It is possible that data grows. On the one hand it is a good feature whenever developers are not sure about size of arraylist and on the other hand it might take long time for size definition.

2. Arraylist is NOT Strongly Typed -> Whenever developers are not sure about what is exactly type definition for input or output data and they should wait until runtime to appear its type. Its advantage is time consuming at the runtime for memory to determine type definition.

3. Developers use “foreach” keyword to fill and iterate through arraylist.

img1

img1

HashTable

HashTable is another kind of data structure that defines key value for each data section. Therefore finding data is easy just by point out to its key. It is NOT strongly typed and NOT fixed size.

img1

Stack

We have different data structure and stack is one of them. Stack is subset of data structure. Stack is prioritized data structure (such as List is indexed base). Stack defines priority for each item, it means stack behavior force its items to put (push) inside stack prioritized form. So stack put later item on the top of items and this behavior is “defining priority for each item”. Therefore whenever you want to insert item, you should add (PUSH) it at the top of the stack and whenever you want to remove (POP) item from stack you should remove it from top of the stack. As you got it, item that comes last one will be selected to POP for first one and its expression in computer science is equal to “Last in First out” == “LIFO”.

It is NOT strongly typed and NOT fixed size.

 

img1

Queue

Queue is another kind of data structure that defines priority for each item in other form. Therefore whenever you want to insert item, you should add (Enqueue) it at the head of the queue and whenever you want to remove (Dequeue) item from queue you should remove it from bottom of the queue. As you got it, item that comes first one will be selected to Dequeue for first one and its expression in computer science is equal to “First in First out” == “FIFO”.

It is NOT strongly typed and NOT fixed size.

img1

List

Why we need List?

1. List is NOT Fixed Length -> It is possible that data grows. On the one hand it is a good feature whenever developers are not sure about size of arraylist and on the other hand it might take long time for size definition.

2. List is Strongly Typed when it is defined “Generic” -> Whenever developers are sure about what is exactly type definition for input or output data and they do not wait until runtime to appear its type. This feature makes to run fast at runtime, since it does not need to wait for type definition.

3. Developers use “foreach” keyword to fill and iterate through array.

Since List is not Fixed Length makes developers feel flexible to use it, and because of it is Strongly Typed when it is defined “Generic” so our code runs fast at runtime because it does not need to wait for type definition.

 

img1

IList

Why we need IList? IList is implemented by List, Ilist is an interface and implements methods. Whenever you estimate probability that your code would be changed in future you have to use IList because interface reduces dependency and with the little modification your code runs. Therefore you should observe polymorphism in order to decouple your app and control on adding or removing method that might be changed. Everything else is similar. Whenever we want to change on some operation, so “IList” allow us to do that easily with at least changing in the whole of codes.

Interfaces can not be instantiate, so it should be instantiate from List

System.Collections.Generic.IList<string> strIList = new List<string>();

Difference between Concrete Class and Interface

1. Concrete Class inherits from just ONE class but Interface implements from one or MORE than one interfaces

2. You can write inside concrete class full version of your function while you have to define just signature inside the interface.

3. You can define variable and value Inside Concrete Class while you are not allowed to define variable inside interfaces.

4. An Concrete class can have constructor while you are not allowed to define constructor inside interfaces.

5. Abstract class can containe access modifier while intefaces does not.

As I mentioned that how a class cannot be driven from two class it just can be driven from only one class, so whenever you want to drive from two class it is not possible to inherit from two abstract class but it is possible to drive from more than one class by interfaces.

Later in future if developers decide to add some features on their class and inherit it from another class, developers always prefer to use interface of collection so that if you want to change your code and enhance its abilities, choose interfaces.

On the other hand interface keeps your program extensible and Decouple: The classes are independent from each other, so error, exception and failure will happen rarely in future changing code by interfaces.

Polymorphism: When you are using interface you absolutely observe and do polymorphism and oop. It means encapsulate your designer. Interface means a point or a node to join two part to each other it means making low dependency from two part and make a joint section to make flexible change in future.

img1

IEnumerable

IEnumerable is suitable just for iterate through collection and you can not modify (Add or Remove) data IEnumerable bring ALL data from server to client then filter them, assume that you have a lot of records so IEnumerable puts overhead on your memory.

img1

IQueryable

Whenever we encounter to huge data with so many records so we have to reduce overhead from application. IQueryable prepares high performance in such situations (huge data) by filtering data firstly and then sending filtered data to client.

 

Follow “Entity Framework DatabaseFirst” from this article for making DBContext

DataAccessEntities ctx = new DataAccessEntities();
        var ctx = new DataAccessEntities();

Data Access

SQL Profiler:

How to trace your query generates TSQL & How many records will be loaded:

Step 1:

Start -> MS SQL Server 2008 -> Performance Tools -> SQL Server Profiler

Step 2:

SQL Server Profiler -> File -> New Trace

Step 3:

Connect with you user name and password.

Step 4:

General (Tab) -> Use the Template: Standard

Step 5:

Event Selection (Tab) -> Event : TSQL -> Select : SQL-BatchCompleted | Select Show all Columns

Press Column Filter -> Database Name: Like: “DataAccess”

Press Run

Step 6:

Go To MS SQL Server Management Studio -> Count all of records (records=5)

Step 7:

IEnumerable generates:

SELECT 
[Extent1].[ID] AS [ID], 
[Extent1].[Name] AS [Name], 
[Extent1].[Age] AS [Age]
FROM [dbo].[Employee] AS [Extent1]

 

IQueryable generates:

SELECT 
[Extent1].[ID] AS [ID], 
[Extent1].[Name] AS [Name], 
[Extent1].[Age] AS [Age]
FROM [dbo].[Employee] AS [Extent1]
WHERE 1 = [Extent1].[ID]

ICollection

ICollection inherits from IList. There is one difference:

you can find IList[ i ] –> Index Based

you can NOT find ICollection[ i ] –> Not Index Based

img1

Dictionary and IDictionary

Dictionary is GENERIC while HashTable is not generic : Dictionary<TKey, TValue>, There is a tiny difference between them that if dictionary can not find specific key will throw an exception while HashTable just returns null.

IDictionary is interface and if you estimate big changes in future use IDictionary instead of Dictionary.

img1

References

msdn.microsoft.com: Commonly Used Collection Types

http://www.codeproject.com/Articles/732425/IEnumerable-Vs-IQueryable

http://www.dotnet-tricks.com/Tutorial/linq/I8SY160612-IEnumerable-VS-IQueryable.html

http://www.claudiobernasconi.ch/2013/07/22/when-to-use-ienumerable-icollection-ilist-and-list

http://www.dotnetperls.com/

Source : CPOL

Feedback

Feel free to leave any feedback on this article; it is a pleasure to see your comments and vote about this code. If you have any questions, please do not hesitate to ask me here.

Advertisements

1 Comment »

  1. I used too be recommended this blog through my cousin. .

    You’re wonderful! Thank you!

    Comment by Kandice — 10/May/2016 @ 8:38 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: