2012-07-27 114 views
1

我有一個DataTable(id),它有一列(LinkID)。此列的行中的項目是數字。我試圖按以下格式列出這些數字:Listing DataTable values

1, 2, 30, 494, etc... 

我將如何得到所有數字並以這種方式列出它們?

這是我曾嘗試:

foreach (DataRow row in id.Rows) 
{ 
    foreach (DataColumn column in id.Columns) 
    { 
     var test = row[0].ToString(); 
     List<string> ls = new List<string>(); 
     ls.Add(test); 
     MessageBox.Show(ls.ToString()); 
    } 
} 

回答

4

您可以執行以下操作:

List<string> test = new List<string>(); 

foreach (DataRow row in id.Rows) 
{ 
    test.Add(row[0].ToString()); 
} 

MessageBox.Show(String.Join(",", test.ToArray())); 
3

既然你知道你只有在表一個列,我建議循環和使用StringBuilder建立您的字符串,如下所示:

var builder = new StringBuilder(); 

// Cycle through the rows, append the field. 
var query = 
    from row in id.AsEnumerable() 
    select builder.Append(row.Field<int>(0)).Append(", "); 

// Get the last or default, if there are no rows, builder will be null. 
builder = query.LastOrDefault(); 

// If the builder is null, there are no rows, return 
// null. 
if (builder == null) return null; 

// The builder is not null, there is content 
// in the StringBuilder. 
// This removes the last ", " which is appended at the end if 
// there are any elements. 
if (builder != null) builder.Length -= 2; 

// Return the string from the builder. 
return builder.ToString(); 

由於StringBuilder.Append method使用fluent interface,因此您可以讓LINQ查詢返回相同的實例,並在繼續附加逗號分隔值時獲取最後一個實例。

您使用LastOrDefault method,以便如果沒有行,則會得到一個null值,表示您沒有行。

你在這裏有兩個好處;對於大量的行,你不建立一個你必須稍後連接的字符串列表。相反,您正在構建字符串,並根據需要將StringBuilder(其預先分配容量)的容量相加。

另外,不必在末尾調用Array.Join(或某些其他字符串連接方法),您最終會再次省略額外的級聯操作