How to shuffle a row in C#


In this post, I will show you how to shuffle the row of any collection in C#. In this post, I am using DataSet, but you can apply this logic anywhere like List. Check out the following code snippet.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Randomize.aspx.cs"  
Inherits="Randomize" %>  

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  

<html xmlns="http://www.w3.org/1999/xhtml" >  
<head runat="server">  
<title>Untitled Page</title>  
</head>  
<body>  
<form id="form1" runat="server">  
<div>  
<asp:GridView ID="grd" runat="Server"></asp:GridView>  
</div>  
</form>  
</body>  
</html>  
using System;  
using System.Data;  
using System.Configuration;  
using System.Collections;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Web.UI.HtmlControls;  

public partial class Randomize : System.Web.UI.Page  
{  
protected void Page_Load(object sender, EventArgs e)  
{  
    grd.DataSource = DataSetUtilities.RandomizeDataTable(CreateDS().Tables[0]);  
    grd.DataBind();  

}  
private DataSet CreateDS()  
{  
    DataSet ds;  
    if (Session["DataList_ParentChild"] == null)  
    {  
        ds = new DataSet();  
        DataTable dt = new DataTable("Company");  
        DataRow dr;  
        dt.Columns.Add(new DataColumn("ID", typeof(Int32)));  
        dt.Columns.Add(new DataColumn("CompanyName", typeof(string)));  
        dt.Columns.Add(new DataColumn("Address", typeof(string)));  
        dt.Columns.Add(new DataColumn("Name", typeof(string)));  
        dt.Columns.Add(new DataColumn("Dept", typeof(string)));  
        for (int i = 1; i < 10; i++)  
        {  
            dr = dt.NewRow();  
            dr[0] = i;  
            dr[1] = "Company " + i;  
            dr[2] = "Address " + i;  
            dr[3] = "Manager name";  
            dr[4] = "Adminstration";  
            dt.Rows.Add(dr);  
        }  
        ds.Tables.Add(dt);  
        DataColumn[] Parent_PKColumns = new DataColumn[1];  
        Parent_PKColumns[0] = dt.Columns["ID"];  
        dt.PrimaryKey = Parent_PKColumns;  

      
    }  
    else  
    {  
        ds = (DataSet)Session["DataList_ParentChild"];  
    }  
    return ds;  

}  

}  
public static class DataSetUtilities  
{  

static Random _rand = new Random();  



public static DataView RandomizeDataTable(DataTable dt)  
{  

    // Create array of indices and populate with ordinal values  

    int[] indices = new int[dt.Rows.Count];  

    for (int i = 0; i < indices.Length; i++)  

        indices[i] = i;  



    // Knuth-Fisher-Yates shuffle indices randomly  

    for (int i = indices.Length - 1; i > 0; i--)  
    {  

        int n = _rand.Next(i + 1);  

        int tmp = indices[i];  

        indices[i] = indices[n];  

        indices[n] = tmp;  

    }  



    // Add new column to data table (if it's not there already)  

    // to store shuffle index  

    if (dt.Columns["rndSortId"] == null)  

        dt.Columns.Add(new DataColumn("rndSortId", typeof(int)));  

    int rndSortColIdx = dt.Columns["rndSortId"].Ordinal;  

    for (int i = 0; i < dt.Rows.Count; i++)  

        dt.Rows[i][rndSortColIdx] = indices[i];  



    DataView dv = new DataView(dt);  

    dv.Sort = "rndSortId";  

    return dv;  

}  

}

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru