如何使用string.Join将Jagged数组与分隔符连接?

时间:2010-06-20 07:03:06

标签: c# .net visual-studio visual-studio-2008

我如何解决下面的字符串连接错误。我将int值转换为字符串值但发生错误....查看连接方法

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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

您只想依次获取所有值?那么SelectMany可能有所帮助。如果你使用的是.NET 4,那么Join重载也可以在这里提供帮助(采用序列而不是数组,因此您不需要创建额外的单个数组,或者使用{{ 1}}):

StringBuilder

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