-1

I have a piece of code that automatically removes all the dashes if the ID isn't null. It was brought to my attention that these also need to always have 9 numbers. However when you lead with zeros the 0's are automatically cut off. How do I add another condition to the id. Something like

if i.id.length < 9 add 0's to the front until it equals 9?

Original code

retval.Add(new SpreadsheetColumnSetup<Row>("ID", i =>
    (i.Id == null)
        ? i.Id
        : i.Id.Replace("-", "")));
Rufus L
  • 36,127
  • 5
  • 30
  • 43
Cecily
  • 61
  • 1
  • 5
  • ints.Add(new object("ID", i => (i.Id == null ? i.Id : i.Id.Replace("-", "") && i.Id.Length < 9 ? ..append zeros ))); – Lyubomir Dimov Mar 22 '17 at 23:09
  • "However when you lead with zeros the 0's are automatically cut off. " Cut off by what? Are you saying that you are setting it to a string that contains the leading zeroes, but they are being removed somehow? – John Wu Mar 23 '17 at 00:46

2 Answers2

3

You can use string.PadLeft():

i => (i.Id == null ? i.Id : i.Id.Replace("-", "").PadLeft(9, '0'))
itsme86
  • 19,266
  • 4
  • 41
  • 57
3

Use PadLeft method as @itsme86 suggested. You can also simplify overall lambda with null conditional operator if you are using C# 6+

i => i.Id?.Replace("-", "").PadLeft(9, '0')
neer
  • 4,031
  • 6
  • 20
  • 34
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459