我会解释, 我正在做一个简单的琐事。 我需要在一个数组中得到3个错误答案和1个正确答案。 我声明哈希表并用数据填充它:
private static readonly HashSet<string> DifferentAnswers= new HashSet<string>();
此HashSet包含类别的所有可能答案,包括正确答案。
目前,我正在执行以下操作以获得3个错误答案:
注意:CorrectAnswer
变量是字符串类型中的绝对正确答案
DifferentAnswers
.OrderBy(n => Guid.NewGuid())
.Take(3)
.Where(n => n != CorrectAnswer)
.ToArray();
有没有办法在1个花式Linq(共4项)中以不同的顺序将3个不正确的答案和1个正确的答案输入数组? :)
之后我将检查阵列中正确答案的数量。
答案 0 :(得分:2)
你可以“联合” IEnumerable的其他项目列表,但您可能希望事后重新洗牌:
DifferentAnswers
.OrderBy(n => Guid.NewGuid())
.Where(n => n != CorrectAnswer)
//Needs to be after the Where
.Take(3)
// added:
.Concat(new [] {CorrectAnswer})
.OrderBy(n => Guid.NewGuid())
//
.ToArray();
(当然,它假设您事先了解CorrectAnswer
,就像您建议的示例代码一样)
答案 1 :(得分:0)
看看这是否有帮助:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication51
{
class Program
{
public class Question
{
public int number { get; set; }
public string question { get; set; }
public string answer { get; set; }
public List<string> wrongAnswer { get; set; }
}
static void Main(string[] args)
{
List<Question> test = new List<Question>() {
new Question() { number = 1, question = "Question 1", answer = "Answer 1", wrongAnswer = new List<string>() { "Wrong Answer 1","Wrong Answer 2","Wrong Answer 3"}},
new Question() { number = 2, question = "Question 2", answer = "Answer 2", wrongAnswer = new List<string>() { "Wrong Answer 1","Wrong Answer 2","Wrong Answer 3"}},
new Question() { number = 3, question = "Question 3", answer = "Answer 3", wrongAnswer = new List<string>() { "Wrong Answer 1","Wrong Answer 2","Wrong Answer 3"}},
new Question() { number = 4, question = "Question 4", answer = "Answer 4", wrongAnswer = new List<string>() { "Wrong Answer 1","Wrong Answer 2","Wrong Answer 3"}},
new Question() { number = 5, question = "Question 5", answer = "Answer 5", wrongAnswer = new List<string>() { "Wrong Answer 1","Wrong Answer 2","Wrong Answer 3"}}
};
Random rand = new Random();
var results = test.OrderBy(x => x.number).Select(x => new List<KeyValuePair<int,string>>() { new KeyValuePair<int,string>(rand.Next(), x.answer), new KeyValuePair<int,string>(rand.Next(), x.wrongAnswer[0]),new KeyValuePair<int,string>(rand.Next(), x.wrongAnswer[1]),new KeyValuePair<int,string>(rand.Next(), x.wrongAnswer[2])})
.Select(x => x.OrderBy(y => y.Key).Select(y => y.Value).ToList()).ToList();
}
}
}