Init array of type with lambda

2019-06-02 04:20发布

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?

标签: c# lambda
1条回答
The star\"
2楼-- · 2019-06-02 05:01

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();
查看更多
登录 后发表回答