LINQ to Objects - Refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly without the use of an intermediate LINQ provider such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array or Dictionary<Tkey, TValue>. The collection can be user defined or returned by a .NET framework API.
LINQ queries advantages over traditional foreach loops:
Below are the few examples where LINQ to Objects can be applied.
LINQ queries advantages over traditional foreach loops:
- In LINQ queries, you write declarative code that describe what you want to retrieve unlike old ways where you had to write complex foreach loops that specified how to retrieve data from collection.
- Filtering data using LINQ queries is more concise and readable, especially when filtering multiple conditions.
- LINQ queries provide powerful filtering, ordering, and grouping capabilities with a minimum of application code.
- LINQ queries can be ported to other data sources with little or no modification.
Below are the few examples where LINQ to Objects can be applied.
- LINQ and String - LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. Example:
To see more examples of "LINQ and String" refer MSDN.
- LINQ and Non-generic Collection - When using LINQ to query non-generic IEnumerable collections such as ArrayList, you must explicitly declare the type of the range variable to reflect the specific type of the objects in the collection. Example:
- LINQ and Custom Methods - We can add custom methods for the LINQ queries by adding extension methods to IEnumerable<T> interface. Few example of such existing methods are Distinct<TSource>, Skip<TSource> and Reverse<TSource> etc. Below is the example of new custom method (Extension Method) and this method is only available for IEnumerable<double> not for any IEnumerable<T>.
To make the above method available for any type, make a generic overload of same method by making source as IEnumerable<T> and adding a new parameter of type delegate Func<T, TResult>, this delegate takes an object of type T and returns double.
- LINQ and File Directories - Many file system operations are essentially the queries and are therefore well-suited to the LINQ approach. To view the various examples of "LINQ & File Directories" refer MSDN.
No comments:
Post a Comment