0

hiee every one, i am developing a small application from where all questions are coming randomly.

i have use the default random method to get random data but it gives duplicate rows twice. so what i need is to get distinct rows into data table.

i am using following method to get rendom records...

 Random rDom = new Random();
 dtRandom = dt.Clone();
 int rw = 0;
 for (int ctr = 1; ctr <= dt.Rows.Count; ctr++)
 {
        rw = rDom.Next(1, dt.Rows.Count);
        dtRandom.ImportRow(dt.Rows[rw]);
 }
 dtRandom.AcceptChanges();

so, how can i achieve distinct records from datatable ?

immayankmodi
  • 8,210
  • 9
  • 38
  • 55

2 Answers2

1

As you are aware, random number generation may generate the same number multiple times. Either check for the existence of the imported row before importing it into your datatable, if there is a unique surrogate key / primary key. Otherwise you can use this approach to get the distinct values from the final DataTable:

DataTable distinctTable = new DataView(dtRandom).ToTable(
  true, new string[] { "column1", "column2", "etc." });

From http://msdn.microsoft.com/en-us/library/wec2b2e6.aspx

Shan Plourde
  • 8,528
  • 2
  • 29
  • 42
  • i know its a tricky think to do and it takes more overhead cost with optimization but truth is that it helped me instead my project is small so not mind with it. Thanks once again. !! – immayankmodi Jan 31 '13 at 05:19
-3

You need to keep the same Random object.
Put it outside your static method as a static member

private static Random rand = new Random();

public static int rInt(int exclUB, int incLB = 0)
{
    int t = rand.Next(incLB, exclUB);
    return t;
}

Detail

Random Number Generation - Same Number returned

Community
  • 1
  • 1
शेखर
  • 17,412
  • 13
  • 61
  • 117