Sunday, 11 March 2012

How to iterate through Linq(Language Integriated Query)?


Yes,till now we fetch the data from object from object oriented style like Obj.adfasnamobject dot name of the column but now using Linq way of style query object data.

       List<int> arrlist = new List<int>();
           arrlist.Add(10);
           arrlist.Add(20);
           arrlist.Add(30);
           IEnumerable<int>  y = from m in arrlist select m; // where m == 10 select m;
           IEnumerator<int> ier = y.GetEnumerator();
           while (ier.MoveNext())
           {
               int i = ier.Current;
               Console.WriteLine(i);
          
           }
           Console.WriteLine(y);
           Console.ReadKey();
The best iteration is above rather then using Var instead of  IEnumerable<int>. but we don’t know the the linq query returns the data.
           IEnumerable<int>  y = from m in arrlist  where m > 10 select m;
           IEnumerator<int> ier = y.GetEnumerator();
           while (ier.MoveNext())
           {
               int i = ier.Current;
               Console.WriteLine(i);
          
           }
Output :   20 30

Like now in this case we know that query returns the type of data is Enumerable<T> with specified type.
We can use

Var also instead of IEnumerable<int> in above example;
Note: our linq query if we search  for Integer type then returns -àIEnumerable<int>
linq query if we search  for String type then returns -àIEnumerable<string>…..ect
so most of the times try to use Var keyword.

No comments:

Post a Comment