linq and IEnumerable interface
If you have read the book titled: "Web ERP software" you will have noticed that in the book we queried the database using stored procedures. However, an alternative method of querying is Linq which is more elegant than earlier methods. .Net 3.5 upgraded the querying technology to make it a powerful tool to query any data source. By default all .Net collections implement IEnumerable<T> interface and are eligible for querying by LINQ.
What is IEnumerable<T>interface ?
The IEnumerable<T> interface is an extension of IEnumerable and contains the GetEnumerator() method. The IEnumerator<T> interface is used to iterate through a .net collection. This interface is returned by
GetEnumerator() method. All .Net collections implement The IEnumerable<T> interface and the GetEnumerator() method. The definition of the IEnumerator<T> interface is shown below.
public interface IEnumerable<T>:IEnumerable
{
IEnumerator<T> GetEnumerator();
}
Note : If you want to use LINQ on your custom types, those custom types should implement IEnumerable<T> interface.
What you should note when programming is whether the data source is a .net collection or your custom type which implements IEnumerable<T> interface. When we implement the interface, we will get only the enumerator which knows how to iterate through each item in a collection and return the object. The Where, OrderBy, and Select operators work on collections and data sources that are enumerable.
What collections are enumerable in .net?
Arrays, Dictionaries, Trees, Stacks, Queues, Files in a directory and XML documents are enumerable.
When we use LINQ operators, the query returns IEnumerable<T> type.
When we want to count number of items in a query result, we use the count operator. The count operator uses the enumerator and counts the total number of items.
Similarly, the ToList operator also uses the enumerator and iterates through the query result and adds each item into a new list. So, using LINQ operators we can iterate the results through the enumerator.