从C#中的字符串列表中生成随机字符串? [英] Generate random string from list of string in C#?

查看:51
本文介绍了从C#中的字符串列表中生成随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从字符串数组列表中获取"n"个随机字符串.其中n =我想要从列表中选择的字符串数可以是1,2,3 ....?如果我想选择不重复的四个字符串,假设我有N个字符串的数组列表.我该怎么做?该代码应使用C#.尽管我已经做到了,但是最好的方法是什么?

Get 'n' random string from a Arraylist of string. Where n= number of string I want from the list it can be 1,2,3....? Suppose that I have Array list of N Strings if I want to choose Random four strings without repetition. How can I do it? The code should be in C#. Though I have done this, but What is the best way?

推荐答案

尝试一下:

class Program
{
    static void Main(string[] args)
    {
        int myRandomIndex = 0;
        var myList = new List<string>(new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" });
        var results = new List<string>();
        var r = new Random(DateTime.Now.Millisecond);
        for (int ii = 0; ii < 4; ii++)
        {
            myRandomIndex = r.Next(myList.Count);
            results.Add(myList[myRandomIndex]);
            myList.RemoveAt(myRandomIndex);
        }

        Console.WriteLine(string.Join("", results));
        Console.ReadKey();
    }
}

为使每个选择的字符串保持唯一(防止重复),我将其从使用时的源列表中删除.使用列表之前,还应该执行 myList = myList.Distinct(),以确保开始时没有重复项.

To keep each chosen string unique (prevent duplicates) I remove it from the source list as it is used. You should also do a myList = myList.Distinct() before using the list, to make sure you don't have duplicates in it to begin with.

这篇关于从C#中的字符串列表中生成随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆