5 tips to get started LINQ in C#


1-LINQ is not just for Iteration :

LINQ (Language integrated Query) is not just for queries a collection of objects, but it will be better if you think about it as a data iteration engine. If you called a method that return data of some type that you needed to convert to another datatype before passing it to another method. Assume you have a method A() that return Array of integers and you need to pass this array to method B() that accepts array of string. You should iterate over array items, one by one, to convert it.But with with LINQ you can do that with just one line of code.
Int32[] nums = {23 , 45 , 65 , 23};
String[] numbers = nums.Select(i => i.ToString()).ToArray();

2-Use the var keyword: 

If you are confused about the type of the sequence result of your query and want to get your code to compile use var keyword. Your query will return an IEnumerable sequance of some type but you don't know exactly what is that type so the best choice is using var keyword.

3-Use the Cast or OfType operators for legacy code:

Before introducing Generics collections which enforce the collection to contain items have the same type. The legacy code used ArrayLists which need to explicit cast each item to deal with. We can cast these old collections to be queried by LINQ by using Cast operator or OfType operator.

Cast operator requires all items in the collection to be of the correct type. If any item is unable to be cast to the specified datatype, an exception will be thrown.

ArrayList arrayList = new ArrayList();
arrayList.Add("Item 1");
arrayList.Add("Item 2");
arrayList.Add("Item 3");

IEnumerable<string> items = arrayList.Cast<string>().Where(n => n.Length == 6);
OfType operator will only items with the specified type will be stored in the output IEnumerable<T> sequence and no exception will be thrown.
IEnumerable<string> items = arrayList.OfType<string>().Where(n => n.Length == 6);

4-Don't assume a query is Bug-Free:

In LINQ the query is being called, declared, or defined but not performed. The query actually will take place the first time a result from it is used. in many cases you face a bug in a code that uses the query result and you assume the bug is in that block of code not in the query itself or its result. No the case is your query result causes the bug and you should check the query result first to fix it.

5-Take advantage of Deferred queries:

As we mentioned in tip #4, the query will not performed till you use its result so you can make a query initialization method that get gets called once for the lifetime of the scope and to construct all the queries there. Then you could enumuerate over a particular sequence to get the latest version of the query results as well

Comments

Popular posts from this blog

ASP.Net MVC : ActionLink with bootstrap icon

ASP.Net MVC : Conditional Validation using ValidationAttribute

Android : How to change progress bar color at runtime programmatically?