Home > Software engineering >  How to create List<string> from a string by replacing the character with range of numbers in b
How to create List<string> from a string by replacing the character with range of numbers in b

Time:07-13

Input string: "Hello_World_{0}"

I need to create a string list which is like Hello_World_1,Hello_World_2,Hello_World_3,etc... to the given input range.

I have tried below approach, it's working fine.

string input = "Hello_World_{0}";
List<string> lst = new List<string>();
foreach (int value in Enumerable.Range(1, 10))
{
  lst.Add(string.Format(input,value));
}

Can I achieve the same in one liner using linq?

CodePudding user response:

Select -> Fetches each item from the range of 1 -10. Input string is replaced with each item and creates a list of strings. ToList -> converts this into list.

string input = "Hello_World_{0}";
List<string> lst = Enumerable.Range(1, 10).Select(item => string.Format(input ,item)).ToList();
  • Related