简体   繁体   中英

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.

What I want to do is get 26 (az) rows with ALL letters, but randomize the rows that have the same letters. So I want 26 rows from A to Z, only one A, one B..., and these letters' rows are random. 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.

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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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