0

So I Have a List, but the list is in integer. Like 1, 2, 3, 4, 5,...,10,...100,..

And I want to convert that integer to string with format 00000X.

X is represent the integer. So the list will be 000001, 000002, 000010, 000100, etc.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
James
  • 408
  • 5
  • 20
  • Welcome to Stack Overflow. Which part is causing problems for you at the moment? Is it the converting a whole list in general, or the specific conversion of a number into a particular format? I would separate those two aspects from each other and just focus on one at a time if I were you. – Jon Skeet Nov 28 '18 at 11:18
  • int[] input = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15 }; string output = string.Join(",", input.Select(x => "0x" + x.ToString("x5"))); – jdweng Nov 28 '18 at 11:24

2 Answers2

1

you can achive this by using LINQ. Please check below answer.

        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 10, 100, 1000,10000,99999,100000 };
        var mask = "00000";
        List<string> stringNumbers = numbers.Select(x =>
        {
            if (mask.Length > x.ToString().Length)
            {
                return mask.Substring(0, mask.Length - x.ToString().Length) + x.ToString();
            }
            else return x.ToString();
        }).ToList();
1
List<string> result = new List<string>();  
foreach (int yourNumber in intList) {
    result.Add("0000000".Substring(0, 7 - yourNumber.ToString().Length);
}

Sould work.

You also can do in on one line, intList.ForEach(...

LeBigCat
  • 1,737
  • 1
  • 11
  • 16