Array.Join in .Net?

后端 未结 7 801
挽巷
挽巷 2020-12-10 10:26

Ok, this is a dumb thing that I\'m sure I\'ve done dozens of times but for some reason I can\'t find it.

I have an array... And want to get a string with the content

相关标签:
7条回答
  • 2020-12-10 11:03

    If you have an array of strings you can call String.join(String, String[]). You can use it even if you don't have an array of strings, you just have to be able to convert your objects to strings

    object[] objects = ...
    string[] strings = new string[objects.Length];
    for (int i = 0; i < objects.Length; i++)
      strings[i] = objects[i].ToString();
    string value = String.Join(", ", strings);
    
    0 讨论(0)
  • 2020-12-10 11:10

    It is on the string class

    String.Join(",", new string[] {"a", "b", "c"});
    

    Edit for ints to string

     int[] integers = new int[] { 1,2,3,4,5 };
     String.Join(",", Array.ConvertAll<int, String>(integers, Convert.ToString));
    
    0 讨论(0)
  • 2020-12-10 11:10
    Dim arrStrIds() As String = Array.ConvertAll(arrIntIds, New Converter(Of Integer, String)(
     Function(id As Integer) id.ToString()) )
    
    String.Join(",", arrStrIds)
    
    0 讨论(0)
  • 2020-12-10 11:11

    If you're working with strings, then String.Join is probably what you're looking for.

    0 讨论(0)
  • 2020-12-10 11:16

    You could use LINQ to Objects and save yourself a few lines

    int [] ints = { 0, 1, 2 };
    string[] intStrings = (from i in ints select i.ToString()).ToArray<string>();
    string joinedStrings = string.Join(",", intStrings);
    

    Oops, Just saw that you don't have LINQ, sorry.

    0 讨论(0)
  • 2020-12-10 11:21

    you don't need to convert the array into a string array in .NET Framework 4. i don't know about previous Frameworks. so the previous code spends several lines converting your int array into a string array. just skip that step (if it also works in your Framework).

    string[] sA = "11,12,13".Split(',');
    int[] iA = { 21, 22, 23};
    Console.WriteLine(string.Join("+", iA) + " -- " + string.Join("+", sA));
    
    /* displays:
    21+22+23 -- 11+12+13
    */
    
    0 讨论(0)
提交回复
热议问题