简体   繁体   English

如何获取随机AZ字母数组?

[英]How to get array of random A-Z letters?

Let me explain what I mean: I have a database that contains 4 columns, one of which is Letter, so each row has a character from 'A' to 'Z', and these aren't unique, so there are multiple rows with 'A', multiple rows with 'B' etc. 让我解释一下我的意思:我有一个包含4列的数据库,其中一列是Letter,所以每行都有一个从'A'到'Z'的字符,这些不是唯一的,所以有多行包含'A',多行'B'等

What I want to do is get 26 (az) rows with ALL letters, but randomize the rows that have the same letters. 我想要做的是获得包含所有字母的26(az)行,但随机化具有相同字母的行。 So I want 26 rows from A to Z, only one A, one B..., and these letters' rows are random. 所以我想要从A到Z的26行,只有一行A,一行B ......,这些字母的行是随机的。 I hope you guys can understand what I mean. 我希望你们能理解我的意思。 Thanks in advance! 提前致谢!

I was thinking something like: 我想的是:

var randomQuestions = questions.Distinct().GroupBy(q => q.Letter).Take(26).ToArray();

But I have no idea really. 但我真的不知道。

If I understand the question correctly, something like this should work: 如果我正确理解了这个问题,那么这样的事情应该有效:

Random random = new Random();

var randomQuestions = questions
    .GroupBy(q => q.Letter)
    .SelectMany(g => g.Skip(random.Next(g.Count())).Take(1));

The Distinct() in your original effort is useless at best, and counter-productive at worst. 原始努力中的Distinct()充其量只是无用的,最坏的情况是适得其反。

The above simply groups your data by letter, and then selects a random single element from each group. 以上简单地按字母对数据进行分组,然后从每个组中选择一个随机的单个元素。 If you have twenty-six distinct letters in your original data, the above will select one random row of data for each of those distinct letters. 如果原始数据中有26个不同的字母,则上面将为每个不同的字母选择一个随机数据行。 You'll get twenty-six elements in the final result. 你将在最终结果中获得二十六个元素。

I'm going to suggest a slight variation on Peter's excellent answer. 我会建议彼得的优秀答案略有不同。

Try this: 试试这个:

Random random = new Random();

var randomQuestions =
    from q in questions
    orderby random.Next()
    group q by q.Letter into gqs
    from gq in gqs.Take(1)
    select gq;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM