开发者

Init array of type with lambda

开发者 https://www.devze.com 2023-02-18 03:31 出处:网络
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.
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?


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

精彩评论

暂无评论...
验证码 换一张
取 消