在N多条数据中随机取M条

下面的例子是在strList1中的N条记录中随机取M条字符串添加到strList2中:

List<string> strList1 = new List<string>();
List<string> strList2 = new List<string>();

Random rand = new Random();  //调用Random类新建一个随机数生成器
int i = 0;
while (i < M)
{
    int index = rand.Next(N);  //返回一个非负随机数
    if (!strList2.Contains(strList1[index]))
    {
        strList2.Add(strList1[index]);
        i++;
    }
}

 

posted @ 2013-05-27 13:28  爹子王  阅读(223)  评论(0编辑  收藏  举报