user1565077
user1565077

Reputation:

C# Possible lambda in array's content declaration

I have such piece of code:

    string suffix = "wallpapers\\";
    string extenstion = ".jpg";
    string[] wallpapers;

    .....
    void SetWallPapers()
    {
        wallpapers = new string[] {
            suffix + "1" + extenstion,
            suffix + "2" + extenstion,
            suffix + "3" + extenstion,
            suffix + "4" + extenstion,
        };
    }

Is there any variant to make lambda-declaretion in array content like:

( pseudo-code, idea only! )

wallpapers = new string[] { ( () => { for i = 1 till 4 -> suffix + i + extension; } ) }

Any suggestions?

Upvotes: 0

Views: 127

Answers (5)

Khurshid
Khurshid

Reputation: 944

Enumerable.Range(1, 10).Select(a => "string" + a).ToArray();

Upvotes: 0

Adrian Thompson Phillips
Adrian Thompson Phillips

Reputation: 7148

string template = "wallpapers\\{0}.jpg";

string[] wallpapers =
    Enumerable.Range(1, 4)
        .Select(i => string.Format(template, i))
        .ToArray();

Upvotes: 0

Sergei Rogovtcev
Sergei Rogovtcev

Reputation: 5832

No, there is not. If you're ok with generating your array at runtime, use

Enumerable.Range(1, 4).Select(i => string.Format("{0}{1}{2}", suffix, i, extension)).ToArray();

PS Your code can't work anyway, you can't add int to string.

Upvotes: 0

DaveShaw
DaveShaw

Reputation: 52798

You can do it using Linq like so:

wallpapers =
    Enumerable.Range(1, 4)
    .Select(i => String.Concat(suffix, i, extenstion))
    .ToArray();

Upvotes: 0

L.B
L.B

Reputation: 116168

string[] wallpapers = Enumerable.Range(1, 4)
                                .Select(i => suffix + i + extenstion)
                                .ToArray();

Upvotes: 1

Related Questions