أسهل طريقة لنسخ DataView إلى DataTable في C #؟
سؤال
أحتاج إلى نسخ DataView إلى DataTable. يبدو أن الطريقة الوحيدة للقيام بذلك هي التكرار من خلال عنصر DataView حسب العنصر والنسخ إلى DataTable. حتما توجد طريقة افضل.
المحلول
dt = DataView.ToTable()
أو
dt = DataView.Table.Copy()
,
أو
dt = DataView.Table.Clone()
;
نصائح أخرى
لا تعمل الجواب على وضعي لأن لدي أعمدة مع تعبيرات. DataView.ToTable()
سوف نسخ القيم فقط، وليس التعبيرات.
أولا حاولت هذا:
//clone the source table
DataTable filtered = dt.Clone();
//fill the clone with the filtered rows
foreach (DataRowView drv in dt.DefaultView)
{
filtered.Rows.Add(drv.Row.ItemArray);
}
dt = filtered;
لكن هذا الحل بطيئا للغاية، حتى مقابل 1000 صفوف فقط.
الحل الذي عمل بالنسبة لي هو:
//create a DataTable from the filtered DataView
DataTable filtered = dt.DefaultView.ToTable();
//loop through the columns of the source table and copy the expression to the new table
foreach (DataColumn dc in dt.Columns)
{
if (dc.Expression != "")
{
filtered.Columns[dc.ColumnName].Expression = dc.Expression;
}
}
dt = filtered;
لا تنتمي إلى StackOverflow