Elegant approach to get a CSV string from selected data rows in a datagrid
I have a datatable containing system profile names. This table is then assigned as the data source of a data grid where the administrator will mark multiple rows as selected.
I'd like to store the selected profile names as a comma separated string. I was going to do it like this:
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);
}
Whilst the above code works I don't feel it's the most elegant way forward.
Any suggestion on how I could improve it?
You can use this linq query
string AllowedProfiles = profiles.Aggregate(string.Empty, (current, row) => current + string.Format(",{0}", row[1])).Remove(0,1);
精彩评论