Applying Action Delegate
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&开发者_运维知识库lt;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.
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);
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);
}
精彩评论