关于C#中System.Random命令的问题。
我在MVC 4项目中有一个查询,如:
public JsonResult GetQuestions()
{
...
var rnd = new Random();
var selectedData = data.Select(y => new
{
...,
qAnswers = ((y.qA1 != null ? "ab" : "") +
(y.qA2 != null ? "cd" : "") +
(y.qA3 != null ? "ef" : "") +
(y.qA4 != null ? "gh" : "") +
(y.qA5 != null ? "ij" : "")).OrderBy(item => rnd.Next())
});
return Json(selectedData, JsonRequestBehavior.AllowGet);
}
作为查询的结果,我希望看到类似的内容:
ijcdefabgh
但结果是:
["i","a","c","d","g","h","e","f","b","j"]
你知道我的错误在哪里吗?或者我该如何解决?
答案 0 :(得分:1)
你必须创建一个字符串数组,以便将“pair”作为一个字符串,然后将其改组,例如:
var qAnswers = String.Concat(new string[] { (y.qA1 != null ? "ab" : "" ),
(y.qA2 != null ? "cd" : ""),
(y.qA3 != null ? "ef" : ""),
(y.qA4 != null ? "gh" : ""),
(y.qA5 != null ? "ij" : "")}
.Where(item=>!string.IsNullOrEmpty(item))
.OrderBy(item=>rnd.Next()));
答案 1 :(得分:-1)
在发布任何答案之前扩展我的评论:
问题:您通过将一串字符串与+
相加来构建字符串。字符串是一组字符,所以当你OrderBy
实际上是在洗牌时。 (通过C#交互式控制台):
( "ab" + "cd" + "ef" + "gh" + "ij").OrderBy(x => Guid.NewGuid())
> OrderedEnumerable<char, Guid> { 'c', 'i', 'e', 'd', 'a', 'f', 'h', 'b', 'g', 'j' }
解决方案:相反,您需要定义要随机播放的字符串集合:
var ans = new List<string>();
ans.Add("ab");
ans.Add("cd");
ans.Add("ef");
ans.Add("gh");
ans.Add("ij");
qAnswers = String.Join("", ans.OrderBy(x => Guid.NewGuid()))
> "cdijefghab"