Skip to main content
 首页 » 编程设计

c#之从 M 集合中取出 n 个唯一对象

2024年02月20日31虾米哥

我想知道如何在 C# 中完成此任务。例如;

I got 10 questions from which 3 is to be displayed to user for them to type the answer. How can i make the program generate 3 questions that are non-repeating(unique) assuming the 10 questions that we are starting with is unique.

我在 asp.net 应用程序中使用逻辑,并且允许在下次刷新页面时显示同一组问题,所以这对我来说没问题。

请您参考如下方法:

为您的问题实例使用一个列表,并随机选择一个(按索引)。然后将其从列表中删除并重复。像这样;

    static void Main(string[] args) 
    { 
        List<string> questions = new List<string>(); 
        for (int i = 0; i < 10; i++) 
            questions.Add("Question " + i); 
 
        Random r = new Random(); 
        for (int i = 0; i < 3; i++) 
        { 
            int nextQuestion = r.Next(0, questions.Count); 
            Console.WriteLine(questions[nextQuestion]); 
            questions.RemoveAt(nextQuestion); 
        } 
    }