Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format String using List of String as an argument in C#

I'm having a List, it contains the Person's Information

C# Code:

List<string> Person = new List<string>() {"Watson", "1001", "Female"};

My Expected String should be

string format = @"Name: {0}({1}) - {2}";
string expectedString = string.Format(format, ......);

I wish to LOOP the List<string> Person as an argument within the method string.Format()

I need to format the string in dynamic not by index number (i.e., static).

The Output should be

string expectedString = "Name: Watson(1001) - Female";
like image 569
B.Balamanigandan Avatar asked Dec 28 '25 00:12

B.Balamanigandan


1 Answers

You can use the string.Format overload that takes a params object array argument, if the list order is guaranteed.

List<string> Person = new List<string>() {"Watson", "1001", "Female"};
string format = @"Name: {0}({1}) - {2}";
string expectedString = string.Format(format, Person.ToArray());

This outputs Name: Watson(1001) - Female

like image 158
David L Avatar answered Dec 30 '25 14:12

David L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!