C#随机排列2个列表

时间:2013-12-12 01:37:19

标签: c#

我一直试图弄清楚如何随机订购两个相同的列表,例如。

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);

现在,如果我想订购这些,以便redhat和redhat图像保持对齐,我怎么能这样做呢?有没有办法组合这些列表,然后使用字典或键值对或其他东西进行随机播放?< / p>

6 个答案:

答案 0 :(得分: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 
        });

..随机化:

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

答案 1 :(得分:1)

您希望将它们放在两个列表中的任何具体原因,您只需创建一个keyvaluepair列表,如下所示:

        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)));

答案 2 :(得分:1)

您可以将数据存储在Tuple<,>中,但如果您有超过2个元素,则只需创建一个显式类来存储数据。

元组示例:

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

答案 3 :(得分:0)

LINQ-fu版本:

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 :(得分: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];
        }
    }
}

答案 5 :(得分: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();