c# 随机化 DataTable 行

c# Randomize DataTable rows

我有一个数据 Table 我正在将其用作中继器的数据源,并希望在每次调用时以随机顺序显示结果。

我已经能够在检索数据时执行此操作,但希望在绑定之前缓存结果集。

在绑定到中继器之前,是否要随机化或随机化数据行 table?

代码:

        TreeProvider tp = new TreeProvider();
    DataSet ds = new DataSet();
    string sKey = "KEY";
    using (CachedSection<DataSet> cs = new CachedSection<DataSet>(ref ds, 5, true, null, sKey))
    {
      if (cs.LoadData)
      {
        ds = tp.SelectNodes("", "URL", "", true, "DOCTYPE", "", "NewID()", -1, true, 5);
        cs.Data = ds;
      }
    }
    if (!DataHelper.DataSourceIsEmpty(ds))
    {
      rprItems.DataSource = ds.Tables[0].DefaultView;
      rprItems.DataBind();
    }

感谢任何指导。

你可以试试这样的东西,我知道它不漂亮但是:

DataTable newTable = new DataTable();
newTable.TableName = "<NewTableName>";
//Make a new Random generator
Random rnd = new Random();
while (<new table length> != <old table length>)
{
    //We'll use this to make sure we don't have a duplicate row
    bool rowFound = false;
    //index generation
    int index = rnd.Next(0, <max number of rows in old data>);
    //use the index on the old table to get the random data, then put it into the new table.
    foreach (DataRow row in newTable.Rows)
    {
        if (oldTable.Rows[index] == row)
        {
            //Oops, there's duplicate data already in the new table. We don't want this.
            rowFound = true;
            break;
        }
    }
    if (!rowFound)
    {
        //add the row to newTable
        newTable.Rows.Add(oldTable.Rows[index];
    }
}

当然,您必须使用自己的表格、名称和长度,但这应该没问题。如果有很多数据,这可能需要一段时间。这是我能想到的最好的,并且未经测试。我很想知道它是否有效。

你可以试试:

        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Sort");
        dt.Rows.Add("TEST");
        dt.Rows.Add("TEST1");
        dt.Rows.Add("TEST2");

        var rnd = new Random(DateTime.Now.Millisecond);
        foreach (DataRow row in dt.Rows)
        {
            row["Sort"] = rnd.Next(dt.Rows.Count);
        }


        var dv = new DataView(dt);
        dv.Sort = "Sort";
        foreach (DataRowView row in dv)
        {
            Console.WriteLine(row[0]);
        }

如果您的数据表不是太大,应该这样做。

我最终复制了 table,添加了一个字段并为每一行分配了一个随机数,然后按该行排序。

        DataTable dt = ds.Tables[0].Copy();
        if (!dt.Columns.Contains("SortBy"))
          dt.Columns.Add("SortBy", typeof (Int32));

        foreach (DataColumn col in dt.Columns)
          col.ReadOnly = false;

        Random rnd = new Random();
        foreach (DataRow row in dt.Rows)
        {
          row["SortBy"] = rnd.Next(1, 100);
        }
        DataView dv = dt.DefaultView;
        dv.Sort = "SortBy";
        DataTable sortedDT = dv.ToTable();

        rprItems.DataSource = sortedDT;
        rprItems.DataBind();