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
    Location
    South Louisiana
    Posts
    10,496

    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:
    Code:
    var parameterIndex = 0;
    var slugs = new[] {"one", "two"};
    var slugParameters = Enumerable.Repeat($"@{parameterIndex++}", slugs.Length);
    Console.WriteLine($" Status IN ({string.Join(", ", slugParameters)})");
    Fiddle: https://dotnetfiddle.net/EnYStx

    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?

    Update
    Apparently using a select works as expected:
    Code:
    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:
    Code:
    $"@{parameterIndex++}"
    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