Thursday, 1 March 2012

How to Enumerate through Arrays and Collections using Linq?


Yes, Using LINQ (Language Integrated and Query) also we can Enumerate through the elements of a array like normal array
              but In Linq  says my return type should be  IEnumerable<T>  [or]  Var
Ex:
     string[] names = { "anand", "balu", "Charan", "deepak" };
    IEnumerable<string> query = from s in names select s;
             // LINQ QUERY return type should be IEnumerable<T>
    IEnumerator<string> ier = query.GetEnumerator(); 
                // must be return type is IEnumerator<T>
          while (ier.MoveNext())
          {
              string str = ier.Current; // from IEnumerable             
              Console.WriteLine(str);         
          }
as well as using List<T> types also we can Enumerable through Like above

            List<string> names=new List<string>();
            names.Add("anand");
            names.Add("balu");
            names.Add("charan");
            names.Add("deepak");
        IEnumerable<string> query = from s in names select s;
        IEnumerator<string> ier = query.GetEnumerator(); 
          // must be return type is IEnumerable<T> 
          while (ier.MoveNext())
          {
              string str = ier.Current; // from IEnumerable              
              Console.WriteLine(str);          
          }

No comments:

Post a Comment