Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - Shuffling string list in C# Windows phone 7

I've looked everywhere on how to shuffle/randomize a string list in C# for the windows phone 7. I'm still a beginner you could say so this is probably way out of my league, but I'm writing a simple app, and this is the base of it. I have a list of strings that I need to shuffle and output to a text block. I have bits and pieces of codes I've looked up, but I know I have it wrong. Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Fisher-Yates-Durstenfeld shuffle is a proven technique that's easy to implement. Here's an extension method that will perform an in-place shuffle on any IList<T>.

(It should be easy enough to adapt if you decide that you want to leave the original list intact and return a new, shuffled list instead, or to act on IEnumerable<T> sequences, à la LINQ.)

var list = new List<string> { "the", "quick", "brown", "fox" };
list.ShuffleInPlace();

// ...

public static class ListExtensions
{
    public static void ShuffleInPlace<T>(this IList<T> source)
    {
        source.ShuffleInPlace(new Random());
    }

    public static void ShuffleInPlace<T>(this IList<T> source, Random rng)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (rng == null) throw new ArgumentNullException("rng");

        for (int i = 0; i < source.Count - 1; i++)
        {
            int j = rng.Next(i, source.Count);

            T temp = source[j];
            source[j] = source[i];
            source[i] = temp;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...