2010-06-20 66 views
4

如何解決下面的字符串連接錯誤。我轉換int值的字符串值,但是會出現誤差....瞧加入方法如何使用string.Join加入帶分隔符的Jagged數組?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 

namespace SortArrayYusuf 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      //int[] array; 

      //using (DataTable table = GetTable()) 
      //{ 
      // array = (from DataRow row in table.Rows 
      //    select 
      //    (from DataColumn col in table.Columns 
      //    select row[col].ToString().Length).Sum()).ToArray(); 
      //} 

      //foreach (int value in array) 
      // Console.WriteLine(value); 

      int[][] lengths; 

      using (DataTable table = GetTable()) 
      { 
       lengths = (from DataRow row in table.Rows 
          select 
          (from DataColumn col in table.Columns 
          select row[col].ToString().Length).ToArray()).ToArray(); 
      } 

      foreach (int[] row in lengths) 
      { 
       Console.WriteLine(string.Join(", ", row.ToString())); 
      } 
      Console.ReadKey(); 
     } 

     static DataTable GetTable() 
     { 
      // 
      // Here we create a DataTable with four columns. 
      // 
      DataTable table = new DataTable(); 
      table.Columns.Add("Dosage", typeof(int)); 
      table.Columns.Add("Drug", typeof(string)); 
      table.Columns.Add("Patient", typeof(string)); 
      table.Columns.Add("Date", typeof(DateTime)); 

      // 
      // Here we add five DataRows. 
      // 
      table.Rows.Add(25, "Indocin", "David", DateTime.Now); 
      table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); 
      table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); 
      table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); 
      table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); 

      return table; 
     } 
    } 
} 

foreach (int[] row in lengths) { Console.WriteLine(string.Join(", ", row.ToString())); }

回答

2
Console.WriteLine(string.Join(", ", row.Select(x => x.ToString()).ToArray())); 
2

你只想把所有的值?然後SelectMany可能會有所幫助。如果你使用的是.NET 4,那麼也有一個Join過載,它也可以在這裏幫助(取一個序列而不是一個數組,因此你不需要創建一個額外的單個數組,或者與StringBuilder混淆):

 int[][] arr = { new[] {1,2,3}, new[] {4}, new[] {5,6}}; 
     string s = string.Join(",", arr.SelectMany(row => row)); 

返回"1,2,3,4,5,6"