我如何将12个名字分成3组,每组4-6次?C#

本文关键字:3组 每组 4-6次 12个 | 更新日期: 2023-09-27 17:58:28

我在C#中有一个程序,需要将12个名称排序为3组,每组4个,共6次,并将它们转储到CSV文件中。它使用textbox作为用户输入,将其放入阵列中并显示在datagrid中。然后程序读取名称并将其放入CSV文件中,还将其显示到另一个datagrid中。下面的代码只执行3组4次,并且按照用户输入的顺序执行。如何在3组(每组4个)中再获得5组随机(或至少有点随机)名称?

public void des()
    {
        for (int x = 0; x < 7; x++)
        {
            //for (int o = 0; o < desArayPlayers.Length; o++)
            {
                int playersCount = 0;
                int k = 0;
                for (int i = 1; i < 4; i++)
                {
                    switch (i)
                    {
                        case 1:
                            k = 0;
                            break;
                        case 2:
                            k = 4;
                            break;
                        case 3:
                            k = 8;
                            break;
                        default:
                            break;
                    }
                    for (int j = k; j < k + 4; j++)
                    {
                        sortingGroupsArayPlayers[playersCount] = "Group " + i.ToString() + "  " + arayPlayers[j];
                        //MessageBox.Show(desArayPlayers[playersCount]);
                        playersCount++;
                    }
                }
            }

        }
    }

我如何将12个名字分成3组,每组4-6次?C#

这将随机排序项目,将它们分组为3组,然后返回组中这些项目的数组集合。

所有这些都发生在for循环中,因此您可以根据需要使用它:)

List<List<int[]>> iterationResults = new List<List<int[]>>();
for (int iteration = 0; iteration < 6; iteration++)
{
    iterationResults.Add(collection.OrderBy(item => Guid.NewGuid())
                .Select((item, index) => new { Item = item, GroupKey = index % 4 })
                .GroupBy(item => item.GroupKey)
                .Select(group => group.Select(item => item.Item).ToArray()).ToList());
}
string[] names = new string[] { "john", "bob", "tim","dickson","bobby","tomson","richard","james","bond","rick","simon","ray" };
Random rnd = new Random();
string[] MyRandomArray = names.OrderBy(x => rnd.Next()).ToArray();
List<string[]> Groups = new List<string[]>();
for (int i = 0; i < 3; i++)//3 groups
   Groups.Add(MyRandomArray.Skip((i)*4).Take(4).Select(x => x.ToString()).ToArray());