2013-12-12 68 views
0

我一直在想如何隨機排列兩個相同的列表,例如。C#隨機排序2列表

List<string> list = new List<string>(); 
list.Add("RedHat"); 
list.Add("BlueHat"); 
list.Add("YellowHat"); 
List<image> list2 = new List<image>(); 
list.Add(Properties.Resources.RedHat); 
list.Add(Properties.Resources.BlueHat); 
list.Add(Properties.Resources.YellowHat); 

現在,如果我想訂購這些使紅帽和紅帽形象保持一致請問有什麼可以做呢?而且是有這些列表合併,然後用字典或鍵值對或東西沿着洗牌的方式那些線?

回答

0

LINQ福版本:

var rng = new Random(); 
var res = Enumerable.Zip(list, list2, (e1, e2) => new { e1, e2 }) 
    .OrderBy(x => rng.Next()) 
    .Aggregate(new { list1 = new List<string>(), list2 = new List<image>() }, 
    (lists, next) => 
    { 
     lists.list1.Add(next.e1); 
     lists.list2.Add(next.e2); 
     return lists; 
    }); 

list = res.list1; 
list2 = res.list2; 
4

包裹兩個對象:

class WrapperObject { 
    public string Name { get; set; } 
    public object Resource { get; set; } 
} 

它們添加到列表:

var list = new List<WrapperObject>(); 
list.Add(new WrapperObject() { 
      Name = "RedHat", 
      Resource = Properties.Resources.RedHat 
     }); 

..randomize:

var rnd = new Random(); 
list = list.OrderBy(x => rnd.Next(50)).ToList(); 
+0

我可以使用,這可能但LINQ聲明是「更清潔」的,因爲我所擁有的清單已經在一個單獨的課堂上完成 –

1

你爲什麼要他們在任何特定原因兩個列表,您可以創建如下所示的keyvalue對的列表:

 var list = new List<KeyValuePair<string, image>>(); 
     list.Add(new KeyValuePair<string, image>("RedHat", (Properties.Resources.RedHat))); 
     list.Add(new KeyValuePair<string, image>("BlueHat", (Properties.Resources.BlueHat))); 
     list.Add(new KeyValuePair<string, image>("YellowHat", (Properties.Resources.YellowHat))); 
1

您可以將數據存儲在Tuple<,>中,但是如果您有超過2個元素,那麼值得創建一個顯式類來存儲數據。

元組例如:

List<Tuple<string, image>> list = new List<Tuple<string, image>>(); 
list.Add(new Tuple<string,image>("RedHat", Properties.Resources.RedHat)); 
// etc... 
0

下面的代碼應該做你想要什麼:

var list1 = new List<string> 
{ 
    "RedHat", 
    "BlueHat", 
    "YellowHat" 
}; 

var list2 = new List<int> 
{ 
    1, 
    2, 
    3 
}; 

var combined = list1.Zip(list2, (a, b) => new { a, b }).Shuffle(new Random()).ToList(); 
list1 = combined.Select(i => i.a).ToList(); 
list2 = combined.Select(i => i.b).ToList(); 

你需要以下擴展方法:

public static class ShuffleExtension 
{ 
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng) 
    { 
     T[] elements = source.ToArray(); 
     for (int i = elements.Length - 1; i >= 0; i--) 
     { 
      int swapIndex = rng.Next(i + 1); 
      yield return elements[swapIndex]; 
      elements[swapIndex] = elements[i]; 
     } 
    } 
} 
0

首先提出了相應的元素結合在一起,然後應用隨機順序:

var rnd = new Random();  
var ordered = list.Zip(list2, Tuple.Create).OrderBy(el => rnd.Next()).ToArray(); 

您可以方便地提取回各列表,如果需要的話:

var ordered_list = ordered.Select(tuple => tuple.Item1).ToList(); 
var ordered_list2 = ordered.Select(tuple => tuple.Item2).ToList();