[英]pick a random records from a datatable
I'm trying to create an application which import an excel file and read the data from it and it returns n records randomly as winners according to how many winners the user want from that list.我正在尝试创建一个应用程序,该应用程序导入一个 excel 文件并从中读取数据,并根据用户希望从该列表中获得的获胜者数量随机返回n条记录作为获胜者。 so i read the data from excel file and assign it to a
datatable
called dt
.所以我读从Excel文件中的数据并将其分配给一个
datatable
叫做dt
。 here is a small overview这是一个小概述
thats the first 30 records in the excel which will be imported to dt
.这是将导入到
dt
的 excel 中的前 30 条记录。 now if user key in 10(thats the total number of winners), i need to pick 10 winners "RANDOMLY" from this dt
, but as you can see some of them are duplicated for example: in column D, the entry named "H" has 6 rows.现在,如果用户输入 10(即获胜者的总数),我需要从这个
dt
“随机”挑选 10 个获胜者,但正如您所看到的,其中一些是重复的,例如:在 D 列中,名为“H”的条目" 有 6 行。 now if the application chose 1 of them, the others "H" have to be removed but that is after it has been chosen.现在,如果应用程序选择了其中的 1 个,则必须删除其他的“H”,但这是在选择之后。 removing the duplicates before choosing any of them, will lower the chance for them to win better prizes.
在选择任何一个之前删除重复项,将降低他们赢得更好奖品的机会。
Could you try something like,你能不能试试
dt2 = dt.Clone();
dt.AsEnumerable().Select(x => x["IC_NUMBER"].ToString()).Distinct().ToList().ForEach(x =>
{
DataRow[] dr = dt.Select("IC_NUMBER = '" + x + "'");
dt2.ImportRow(dr[0]);
dr.ToList().ForEach(y => dt.Rows.Remove(y));
dt.AcceptChanges();
});
EDIT:编辑:
int totalWinners = 10;
Random rnd = new Random();
dt2 = dt.Clone();
for (int i = 1; i <= totalWinners; i++)
{
//Pick random datarow
DataRow selectedWinner = dt.Rows[rnd.Next(0, dt.Rows.Count - 1)];
//Insert it in the second table
dt2.ImportRow(selectedWinner);
//Retrieve other datarows that have same 'IC NUMBER'
var rows = dt.AsEnumerable().Where(x => x["IC NUMBER"].ToString() ==
selectedWinner["IC NUMBER"].ToString());
//Delete all the rows with the selected IC NUMBER in the first table
rows.ToList().ForEach(y => dt.Rows.Remove(y));
dt.AcceptChanges();
}
Hope this helps...希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.