2016-10-07 5 views
2

我想創建一個DataTable含有細胞系> 1. (FYI:新的C#,不知道OOPS什麼...請善待) 這是我的代碼:如何添加「String []或列表<String>」作爲C#中的DataTable中的一個單元格項?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Data; 
using System.IO; 
namespace Excelapp 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     DataTable table = new DataTable(); 
     table.Columns.Add("LOCarray",typeof(String[])); 
     table.Columns.Add("LOCstring", typeof(String)); 
     table.Columns.Add("LOClist", typeof(List<String>)); 


     String[] LOCarray = new String[2] {"Line1","Line2" }; 
     String LOCstring = "Line1\n\rLine2"; 
     List<String> LOClist = new List<String>(); 
     LOClist.Add("Line1"); 
     LOClist.Add("Line2"); 

     table.Rows.Add(LOCarray, LOCstring, LOClist); 

     } 
    } 
} 

輸出是:

DataSet Visualizer enter image description here

正如你所看到的,這不是我想要的。即使當我以String形式書寫時,它也不會顯示\ n字符。

請幫幫我。

+1

你給你*不*想要什麼,但什麼都* *您希望它看起來像? –

+0

'DataTable'是一個結構,而不是一個顯示組件,所以你的'\ n'不會被渲染。當您在可視化工具中查看數據時,它將刪除轉義字符。如果您閱讀該行並將其顯示在文本組件或控制檯中,您將看到新行。 – Alex

+0

你應該在行 – Shrey

回答

2
string[] arr = { "one", "two", "three" }; 

string arrayValuesWithNewLineSep = string.Join("\n", arr)); 
+0

他提到了一些不顯示「\ n」字符的內容,我不相信這是他正在尋找的答案。 –

+0

@BradleyUffner謝謝沒有閱讀這部分。 – mybirthname

+0

這仍然是唯一明智的答案。 OP將數據表與網格混淆。 –

0

如果您喜歡Linq的另一個解決方案是使用Aggregate函數。

例子:

IEnumerable<string> collection = new List<string>() { "This", "is", "a", "sentence", "."}; 

var sentence = collection.Aggregate((a, b) => a + " " + b); 

或者在你的情況,這將會是

var myValue = locList.Aggregate((a, b) => a + "\n\r" + b); 
相關問題