1

i try to convert list to string. but i get error and i try to do it but is to long and i want your help

what i try to do:

List<string> list = new List<string> {"a","a","a" };

i want to get string like this:

my string will be equal to:

"["a","a","a"]" 

how i can do it in one line?

thanks!!!!!!

3
  • 2
    Your format is almost JSON. Are you familiar with JSON? Would serializing it to JSON be sufficient for you?
    – mason
    Mar 31, 2020 at 18:24
  • 1
    mabye i need to try
    – liran
    Mar 31, 2020 at 18:25
  • 12
    "[\"" + String.Join("\",\"", list) + "\"]";
    – 001
    Mar 31, 2020 at 18:27

2 Answers 2

6

how i can do it in one line?

Are you of the opinion that you will live longer if you type fewer lines?

The way to "do it in one line" is to break the problem down into many sub-problems, each of which is short. For example, we could solve your problem by extracting these sub-problems:

Quote a string:

static class Extensions
{
  public static string Quote(this string s) => 
    "\"" + s + "\"";

Quote a sequence of strings:

  public static IEnumerable<string> QuoteAll(
    this IEnumerable<string> items) =>
    items.Select(Quote);

Comma-separate a sequence:

  public static string CommaJoin<T>(this IEnumerable<T> items) =>
    string.Join(",", items);

Bracket a string:

  public static string Bracket(this string s) =>
    "[" + s + "]";
}

And now put it together:

string result = list.QuoteAll().CommaJoin().Bracket();

And you're done "in one line". But the important thing is not that every method is one line. The important things are that first, the meaning of the code can be clearly understood by simply reading it, and second now you have four tools you can use for other jobs in your program. This is probably not the only comma-separated list you're going to create.

3

You can easily do it by serializing your list into JSON string. Using Newtonsoft.Json library

List<string> list = new List<string> { "a", "a", "a" };
var result = JsonConvert.SerializeObject(list);

Using System.Text.Json API (built-in in .NET Core 3.x, available for .NET Core 2.x and .NET Framework 4.7.2 and 4.8)

List<string> list = new List<string> { "a", "a", "a" };
var result = System.Text.Json.JsonSerializer.Serialize(list);

Using .NET Framework built-in JavaScriptSerializer class (but it's not recommended to use, the first option is preferred)

List<string> list = new List<string> { "a", "a", "a" };
var result = new JavaScriptSerializer().Serialize(list);

All methods will return ["a","a","a"], and they are more clear and convenient rather then manual replacing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.