1
class A
{
        private int p;

        public A(int a)
        {
            p = a;
        } 
}

int[] n = { 1, 2, 3, 4, 5 };

how to make an array of A initialized with values from n using lambda. Its ok to use lambda for that?

1
  • To be picky about the wording: Lambda is only the nice syntax for writing an "inline"/anonymous function like i => new A(i). To use the lambda you must call it or pass it to a method that calls the lambda. LINQ contains many suitable methods for dealing with collections, many of them is preferably called with lambdas as arguments. Your question would make more sense if you replaced "lambda" with LINQ. Commented Mar 20, 2011 at 12:43

1 Answer 1

4

I prefer the LINQ query syntax (there is a lambda behind the scenes but hidden behind syntactic sugar).

(
    from i in n
    select new A(i)
).ToArray();

But you can use the explicit LINQ syntax where you type out the lambda.

n.Select(i => new A(i)).ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

+1 I prefer the second one... With a "general" caveat... If the array is VERY big, please don't do this. ToArray will create a List<T> and then from the List an Array. So it'll waste uselessly much memory (the List).
@xanatos, At least in .NET4 Enumerable.ToArray<T> creates a Buffer<T> and not a List<T> internally. Nevertheless there might be one extra copy step in ToArray<T> compared to ToList<T> if the final array length is not a power of 2. But until profiling has proven that is your problem you don't need to worry about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.