简体   繁体   English

C#随机化DataTable行

[英]c# Randomize DataTable rows

I have a Data Table I'm using as the data source for a repeater and would like to have the results show in a random order each time it's called. 我有一个数据表,用作中继器的数据源,希望每次调用时结果以随机顺序显示。

I've been able to do this while retrieving the data but wish to cache the result set before it's bound. 我能够在检索数据时执行此操作,但希望在绑定结果集之前对其进行缓存。

Is the any was to shuffle or randomise the rows of a data table before binding to the repeater? 在绑定到转发器之前,是不是要对数据表的行进行混洗或随机化?

CODE: 码:

        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();
    }

Any guidance is appreciated. 任何指导表示赞赏。

I ended up taking a copy of the table, adding a field and assigning a random number to each row then ordering by that row. 我最终得到了该表的副本,添加了一个字段并为每行分配一个随机数,然后按该行排序。

        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();

You could try something like this, I know it's not pretty but: 您可以尝试这样的操作,我知道它并不漂亮,但是:

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];
    }
}

You'll have to use your own tables, names, and lengths of course, but this should be ok to use. 当然,您必须使用自己的表,名称和长度,但这应该可以使用。 If there's a lot of data, this could take a while. 如果数据很多,这可能需要一段时间。 It's the best I can come up with, and it's untested. 这是我能想到的最好的,并且未经测试。 I'm curious to know if it works. 我很好奇它是否有效。

You could try: 您可以尝试:

        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]);
        }

If your datatable is not too big it should do it. 如果您的数据表不是太大,那就应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM