tags:

views:

68

answers:

2

Just to understand the collection ,I tried to find the square of each number passed in to a collection.

My Code is (Ofcourse I could have implemented in differ way,Just to know casting itretaions,I have made a dummy implementation).

   static void Main()
   {
      ICollection<int> Present = (ICollection<int>)
                                  a.GetNumbers(new int[]{1,2,3});

       foreach (int i in Present)
       {
                   Console.WriteLine("{0}", i);
       }
   }


  public IEnumerable<int> GetNumbers(int[] Numbers)
  {
     //first trial
     ICollection<int> col = 
                           Array.ForEach(Numbers, delegate { x => x * x; });

     //second trial
     ICollection<int> col = Array.ForEach(Numbers, ( x => x * x ));

     return (IEnumerable<int>)col.GetEnumerator();

  }

What is the problem with Array.ForEach in bothh trails inside GetNumbers() ?

I am receiving "Assignment and call increment is allowed". error.

+2  A: 

Action doesn't return anything, and neither does Array.ForEach - but your lambda expression does, and you're trying to use the result of Array.ForEach despite it being a void method. Try Array.ConvertAll instead, which uses a Converter<TInput, TOutput> (equivalent to Func<TIn, TOut>).

Alternatively, if you want to explore Array.ForEach and Action, do something like:

Array.ForEach(Numbers, x => Console.WriteLine(x * x));

(Also, your first attempt seems to be a mixture of anonymous method syntax and lambda syntax. That won't work.)

Like this:

int[] squares = Array.ConvertAll(numbers, x => x*x);
Jon Skeet
Jon,I Changed my statement inside GetNumbers(..) { return (IEnumerable<int>)Array.ConvertAll(Numbers, ( x => x * x )).GetEnumerator(); } .... In Main() also i have implemented .... IEnumerable<int> Present = (IEnumerable<int>)a.GetNumbers(new int[]{1,2,3}).GetEnumerator(); .... I am receiving casting error "Unable to cast object of type 'SZArrayEnumerator' to type 'System.Collections.Generic.IEnumerable`1[System.Int32]'."
Kalai
Your method is declared to return an `IEnumerable<int>`, not an `IEnumerator<int>` - don't call `GetEnumerator()`. The same is true in your main method. Why are you calling GetEnumerator() at all?
Jon Skeet
A: 

This is a school book example of where the LINQ extensions methods come in handy, why don't you just do this:

public IEnumerable<int> GetNumbers(IEnumerable<int> numbers)
{
    return numbers.Select(x => x * x);
}
Freed
So indirectly you are telling ,even a school boy can achieve this. :) Cool. : ) As i mentioned in my post i tried my possibility in using Array.anyhow i appreciate your answer.
Kalai
I meant to say "text book", as in it being a nice and clean example of where LINQ really shines. No offence.
Freed