2011-05-03 15 views
1

我有一個包含系統概要文件名稱的數據表。然後將該表分配爲數據網格的數據源,其中管理員將多個行標記爲選中狀態。從數據網格中的選定數據行獲取CSV字符串的優雅方法

我想將選定的配置文件名稱存儲爲逗號分隔的字符串。 我打算做這樣的:

string AllowedProfiles = string.Empty; 

// Retrieve the selected profiles from the data grid 
DataRow[] profiles = (this.dgv_SecurityProfiles.DataSource as System.Data.DataTable).Select("profile_OK = 1"); 

// Ensure we have some data to assign to the CSV string 
if(profiles != null && profiles.Length > 0) 
{ 
    // Build the CSV string of the selected names. 
    foreach(DataRow row in profiles) 
    { 
     // Use the second column in the DataTable (first is the check column) 
     AllowedProfiles += string.Format("{0},", row[1]); 
    } 

    // Remove the last comma 
    AllowedProfiles = AllowedProfiles.Substring(0, AllowedProfiles.Length - 1); 
} 

雖然上面的代碼工作,我不覺得這是前進的最優雅的方式。

任何有關如何改善它的建議?

回答

0

你可以使用這個LINQ查詢

string AllowedProfiles = profiles.Aggregate(string.Empty, (current, row) => current + string.Format(",{0}", row[1])).Remove(0,1); 
+0

這正是那種優雅的我一直在尋找。謝謝。我想我需要學習Linq。 – TeamWild 2011-05-03 12:47:08

相關問題