【问题标题】:Shuffling string list in C# Windows phone 7在 C# Windows phone 7 中改组字符串列表
【发布时间】:2011-08-01 02:45:06
【问题描述】:

我到处查看如何在 C# 中为 windows phone 7 随机化/随机化字符串列表。我仍然是初学者,你可以说这可能超出了我的范围,但我正在写一个简单的应用程序,这是它的基础。我有一个字符串列表,我需要将其洗牌并输出到文本块。我有一些我查过的代码,但我知道我错了。有什么建议吗?

【问题讨论】:

标签: c# arrays list windows-phone-7 shuffle


【解决方案1】:

Fisher-Yates-Durstenfeld shuffle 是一种经过验证且易于实施的技术。这是一个扩展方法,它将对任何IList<T> 执行就地随机播放。

(如果您决定要保留原始列表并返回一个新的随机列表,或者返回到act on IEnumerable<T> sequences,就像 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;
        }
    }
}

【讨论】:

  • 现在您将如何将列表中的随机字符串设置为文本块?
  • 如果您只需要一个随机字符串,那么您可能根本不需要重新排列列表;只需从现有列表中选择一个随机字符串:var rng = new Random(); yourTextBlock.Text = yourStringList[rng.Next(yourStringList.Length)];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多