无法重新整理DataTable的行 [英] cannot shuffle rows of DataTable
问题描述
我需要重新整理DataTable的行,因为在我的场景中无法随机访问索引。因此,我的dt1具有必须重新整理的基本数据,而dt是具有重新整理的数据的DataTable。我的代码是:
I need to shuffle rows of DataTable as randomly accessing indexes would not work in my scenario. So I have dt1 having base data which I have to shuffle and dt is the DataTable having shuffled data. And my code is:
int j;
for (int i = 0; i < dt1.Rows.Count - 1; i++)
{
j = rnd.Next(0, dt1.Rows.Count - 1);
DataRow row = dt1.Rows[j];
dt.ImportRow(row);
}
它们没有语法错误,但是当我在运行代码的地方进一步访问dt我有些相同的行被导入两次。我在这里做什么错了?
Their is no syntax error but when I run my code where I further access dt I some of same rows get imported twice. What am I doing wrong here?
推荐答案
DataRow
只能属于一个 DataTable
,使用现有 DataRow
中的值创建一个新的行。
DataRow
can only belong to a one DataTable
, create a new Row with the values from existing DataRow
.
dt.Rows.Add(row.ItemArray);
或
dt.ImportRow(row);
更新:
另一种随机化任何集合的方法(来自此链接)。
Another approach to randomize any collection (From this Link).
public static class Extensions
{
private static Random random = new Random();
public static IEnumerable<T> OrderRandomly<T>(this IEnumerable<T> items)
{
List<T> randomly = new List<T>(items);
while (randomly.Count > 0)
{
Int32 index = random.Next(randomly.Count);
yield return randomly[index];
randomly.RemoveAt(index);
}
}
}
现在您可以将任何集合随机化了
Now you can randomize any collection just by calling this extension function.
var dt = dt1.AsEnumerable()
.OrderRandomly()
.CopyToDataTable();
选中此 示例
这篇关于无法重新整理DataTable的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!