2011-04-07 22 views
0

我已經到處尋找如何在C#中爲Windows Phone 7打亂/隨機化一個字符串列表。我仍然是一個初學者,你可以這樣說,所以這可能是我的出路聯盟,但我正在寫一個簡單的應用程序,這是它的基礎。我有我需要洗牌並輸出到文本塊的字符串列表。我查閱了一些代碼,但我知道我錯了。有什麼建議麼?C#中的字符串清單在Windows Phone 7

+1

HTTP: //stackoverflow.com/search?q=%5Bc%23%5D+shuffle – dtb 2011-04-07 23:21:44

+0

如果你不需要隨機混排,一個簡單的選擇是返回「strings.OrderBy(s => s.GetHashCode() );」 ;) – 2011-04-07 23:43:01

+0

可能重複的[C#:是使用隨機和OrderBy一個很好的洗牌算法?](http://stackoverflow.com/questions/1287567/c-is-using-random-and-orderby-a-good-shuffle -algorithm) – Jon 2011-04-08 00:49:16

回答

3

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; 
     } 
    } 
} 
+0

現在你將如何設置一個隨機字符串從列表到文本塊? – Christian 2011-04-08 02:07:23

+1

如果你只需要一個隨機字符串,那麼你可能根本不需要隨便洗牌;只需從現有列表中選擇一個隨機字符串:var rng = new Random(); yourTextBlock.Text = yourStringList [rng.Next(yourStringList.Length)];' – LukeH 2011-04-08 09:01:40