Saturday, January 29, 2011

How to get single quote & comma separated character set from datatable column: for example we want 'row1','row2','row3' from data table values

How to get single quote & comma separated character set from datatable column:
for example we want 'row1','row2','row3' from data table values but without using looping.

1)
Following method takes 3 times more execution time compare to looping
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();

String[] ArrayResIds =
Array.ConvertAll(DataTable.Select(),
delegate(DataRow row) { return (String)row["ColumnName"]; }
);
string resIDsComaaSep = string.Concat("'",string.Join(",'",ArrayResIds),"'");
sw.Stop();

private static string ConvertToString(DataRow dr) { return Convert.ToString(dr[0]); }

2)
Following method takes 35 times more execution time compare to looping

System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();

DataRow[] myrow = new DataRow[DataTable.Rows.Count];
DataTable.Rows.CopyTo(myrow, 0);
string[] ArrayResIds = Array.ConvertAll(myrow, new Converter(ConvertToString));

string resIDsComaaSep = string.Concat("'", string.Join(",'", ArrayResIds), "'");
sw.Stop();
string timeconsuming = sw.ElapsedTicks.ToString();

3) If oracle or sql available for this functionality than it easy to get comma separated string

--Sample table schema

Create table SchemaID([ID] smallint,SchemaID int NOT NULL)

--Dummy insert statements

Insert into SchemaID values (1,12)Insert into SchemaID values (1,13)Insert into SchemaID values (1,14)Insert into SchemaID values (2,15)Insert into SchemaID values (2,16)Insert into SchemaID values (2,17)Insert into SchemaID values (2,18)

--Solution

Declare @ID varchar(100)
Select @id=Coalesce(@ID + ', ', '') + Cast(SchemaID AS varchar(5)) From SchemaID Where [ID] = 1 SELECT @ID

No comments: