Results 1 to 1 of 1

Thread: [RESOLVED] Increment Operator Not Working in Enumerable.Repeat

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    South Louisiana

    Resolved [RESOLVED] Increment Operator Not Working in Enumerable.Repeat

    I found that using the postfix increment operator in Enumerable.Repeat doesn't increment the underlying variable. See for example:
    var parameterIndex = 0;
    var slugs = new[] {"one", "two"};
    var slugParameters = Enumerable.Repeat($"@{parameterIndex++}", slugs.Length);
    Console.WriteLine($" Status IN ({string.Join(", ", slugParameters)})");

    The output from above is:
    Status IN (@0, @0)
    When I would expect it to be:
    Status IN (@0, @1)
    What causes this behavior and is there a workaround aside from manually looping over the array?

    Apparently using a select works as expected:
    var slugParameters = slugs.Select(slug => $"@{parameterIndex++}");
    But I'm still curious why it doesn't work with Enumerable.Repeat.

    Update #2
    I see why now. It is calling:
    Once and then repeating that result n times.
    Last edited by dday9; Jul 8th, 2021 at 03:21 PM.
    "Code is like humor. When you have to explain it, itís bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Click Here to Expand Forum to Full Width