How to get random entire row in Linq from datatable

I want to get entire random rows from a datatable, but the output should return the other columns as well
For example below is the input:

Col1, Col2,Col3
Apple cash 100123
Banana Money 100234
XXXX ATM 123478
Mango Credit 100238
Fruit Cash 100129

How can be achieve this using linq Query with random row

Excepting Result:
Col1, Col2,Col3
Banana Money 100234
XXXX ATM 123478
Apple cash 100123

Kindly, assist me ASAP.

@neelimaintern

use assign activity and

new system.Random().Next(1,dt_input.RowCount)

later use another assign activity to get the random datarows

dt_input.AsEnumerable.Take(int_numbers).CopyToDataTable

here int_numbers is int32 datatype

1 Like

Hi @neelimaintern


Code:

Dim rand As New Random()

Dim randomIndices = Enumerable.Range(0, Dt.Rows.Count).OrderBy(Function(i) rand.Next()).Take(Dt.Rows.Count)

resultTable = (
    From index In randomIndices.Take(3)
    Select Dt.Rows(index)
).CopyToDataTable()

Invoke Arguments:

Regards

1 Like

Thank you for quick response,
I have tried above query and returning only two rows. Suppose having 50 rows are in datatable and i need to get around 5 entire datarows. how can i achieve it?

to make a more distributed random:

And a receipe

which can also be modified within a variation:

ExtractIndex =
ExtractIndex.Append(myRandom.Next() Mod dtData.Rows.Count).Distinct().toList
dtRandomSet =
ExtractIndex.Select(Function (x) dtData.Rows(x)).CopyToDataTable

EDIT-1:

just set the variable RandomSetSize to 5

RandomRowsInDataTable.zip (4.6 KB)

Hi Neelima,

You can achieve this by using Invoke Code.

You can find the solution attached.
I am also adding the C# code block below, you can paste it after you create the invoke activity with the C# property:

out_DataTable = in_DataTable.Clone();
Random random = new Random();
HashSet selectedIndices = new HashSet();

int numberOfRandomRows = random.Next(1, in_DataTable.Rows.Count-1);
var randomIndices = Enumerable.Range(1, in_DataTable.Rows.Count-1).OrderBy(x => random.Next()).Take(numberOfRandomRows);

foreach (int randomIndex in randomIndices)
{
DataRow selectedRow = in_DataTable.Rows[randomIndex];
out_DataTable.ImportRow(selectedRow);
selectedIndices.Add(randomIndex);
}

Thanks !!

It’s working fine

1 Like

You’re welcome @neelimaintern

Happy Automation!!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.