Init array of type with lambda

2019-06-02 04:18发布

问题:

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:

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();


标签: c# lambda