在C#中的Windows Phone 7洗牌字符串列表 [英] Shuffling string list in C# Windows phone 7
问题描述
我到处找关于如何随机播放/随机字符串列表在C#中为Windows Phone 7,我还是可以这么说这可能是我的出路联赛初学者,但我正在写一个简单的应用程序,这是它的基础。我有我需要重新洗牌,并输出到一个文本块字符串列表。我有位和codeS,我抬头一看片,但我知道我有错。有什么建议?
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?
推荐答案
的费雪耶茨-Durstenfeld洗牌是一个成熟的技术,很容易实现。下面是可以在任何的IList&LT执行就地洗牌的扩展方法; T>
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>
.
(这应该很容易,如果你决定要离开原来的完整列表,并返回一个新的适应,洗牌列表,而不是,或<一个href=\"http://stackoverflow.com/questions/1651619/optimal-linq-query-to-get-a-random-sub-collection-shuffle/1653204#1653204\">act在的IEnumerable&LT; T&GT;
序列,点菜LINQ)
(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;
}
}
}
这篇关于在C#中的Windows Phone 7洗牌字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!