I would like to sort a DataTable
for the first two columns using string.Compare
, because I need to sort by Hungarian language ("hu-HU_technl"
). (C#, .NET 2.0)
If not possible for the first two, is enough for the first column.
I tried THIS...is working...but is with one column DataTable
that I add to a List<string>
and Sort
:
System.Globalization.CultureInfo ci = CultureInfo.GetCultureInfo("hu-HU_technl");
StringComparer comp = System.StringComparer.Create(ci, false);
List<string> fields = new List<string>();
DataTable dt = GetData();
for (int row = 0; row < dt.Rows.Count; row++)
{
fields.Add(dt.Rows[row][0].ToString());
}
fields.Sort(
delegate(string p1, string p2)
{
return string.Compare(p1, p2, false, ci);
}
);
for (int i = 0; i < fields.Count; i++)
{
Console.WriteLine(fields[i].ToString());
}
https://dotnetfiddle.net/39z2QX
Sort multiple column DataTable
for the first two columns using string.Compare
.
Edit: code I tried
//----------------------------------------------Main
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, conn.ConnectionString);
DataSet ds = new DataSet();
dAdapter.Fill(ds, "Holtak");
DataTable tempTable = ds.Tables[0].Clone();
ds = utils.Settings.DataTableSort(ds, "hu-HU_technl");
ds.Tables[0].Columns.Add(new DataColumn("imageUrl", typeof(byte[])));
//----------------------------------------------utils.Settings.DataTableSort
public static DataSet DataTableSort(DataSet dt, string culture)
{
CultureInfo ci = CultureInfo.GetCultureInfo(culture);
StringComparer comp = System.StringComparer.Create(ci, false);
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in dt.Tables[0].Rows)
{
rows.Add(row);
}
rows.Sort(
delegate(DataRow r1, DataRow r2)
{
int result = string.Compare((r1[2] == null ? "" : r1[2].ToString()), (r2[2] == null ? "" : r2[2].ToString()), false, ci);
if (result == 0)
{
result = string.Compare((r1[3] == null ? "" : r1[3].ToString()), (r2[3] == null ? "" : r2[3].ToString()), false, ci);
}
return result;
}
);
DataSet dtresult = dt.Clone();
foreach (DataRow dr in rows)
{
dtresult.Tables[0].Rows.Add(dr.ItemArray);
}
return dtresult;
}
If you want to sort the rows, sort the row, not the values from one column of the rows. When doing a comparison by two values, you do the first comparison and then, if the result is zero (i.e. the two values are equivalent), you do the second comparison.
List<DataRow> rows = new List<DataRow>();
DataTable dt = GetData();
foreach (DataRow row in dt.Rows)
{
rows.Add(row);
}
rows.Sort(
delegate(DataRow r1, DataRow r2)
{
int result = string.Compare((string)r1[0], (string)r2[0], false, ci);
if (result == 0)
{
result = string.Compare((string)r1[1], (string)r2[1], false, ci);
}
return result;
}
);