In C#: Add Quotes around string in a comma delimited list of strings

后端 未结 16 1807
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 08:18

This probably has a simple answer, but I must not have had enough coffee to figure it out on my own:

If I had a comma delimited string such as:

string li         


        
相关标签:
16条回答
  • 2021-01-30 09:01

    For people who love extension methods like me, here it is:

        public static string MethodA(this string[] array, string seperatedCharecter = "|")
        {
            return array.Any() ? string.Join(seperatedCharecter, array) : string.Empty;
        }
    
        public static string MethodB(this string[] array, string seperatedChar = "|")
        {
            return array.Any() ? MethodA(array.Select(x => $"'{x}'").ToArray(), seperatedChar) : string.Empty;
        }
    
    0 讨论(0)
  • 2021-01-30 09:02

    Following Jon Skeet's example above, this is what worked for me. I already had a List<String> variable called __messages so this is what I did:

    string sep = String.Join(", ", __messages.Select(x => "'" + x + "'"));
    
    0 讨论(0)
  • 2021-01-30 09:02

    I think the simplest thing would be to Split and then Join.

    string nameList = "Fred,Sam,Mike,Sarah";
    string[] names = nameList.Split(',');
    string quotedNames = "'" + string.Join("','", names) + "'";
    
    0 讨论(0)
  • 2021-01-30 09:02

    Based off Jon Skeet's example, but modernized for .NET 4+:

    // [ "foo", "bar" ] => "\"foo\"", "\"bar\""  
    string.Join(", ", strList.Select(x => $"\"{x}\""));
    
    0 讨论(0)
  • 2021-01-30 09:03

    Are you going to be processing a lot of CSV? If so, you should also consider using a library to do this. Don't reinvent the wheel. Unfortunately I haven't found a library quite as simple as Python's CSV library, but I have seen FileHelpers (free) reviewed at MSDN Magazine and it looks pretty good. There are probably other free libraries out there as well. It all depends on how much processing you will be doing though. Often it grows and grows until you realize you would be better off using a library.

    0 讨论(0)
  • 2021-01-30 09:03

    Here is a C# 6 solution using String Interpolation.

    string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                           .Select(x => $"'{x}'")
                           .ToList());
    

    Or, if you prefer the C# 5 option with String.Format:

    string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                           .Select(x => String.Format("'{0}'", x))
                           .ToList());
    

    Using the StringSplitOptions will remove any empty values so you won't have any empty quotes, if that's something you're trying to avoid.

    0 讨论(0)
提交回复
热议问题