直接上代码:
/// <summary>
/// 随机分组
/// </summary>
/// <param name="list">列表集合</param>
/// <param name="GroupCount">组数</param>
/// <returns></returns>
public static List<List<string>> RandomizedGroupingArray(List<string> list, int GroupCount = 1)
{
//打乱
Random random = new Random();
list = list.OrderBy(x => random.Next()).ToList();
//分组
var groups = list
.Select((item, index) => new { Item = item, GroupIndex = index % GroupCount })
.GroupBy(item => item.GroupIndex, (key, group) => group.Select(groupItem => groupItem.Item).ToList())
.ToList();
return groups;
}
测试结果:
namespace Test
{
public class Program
{
public static void Main(string[] args)
{
List<string> list = new List<string>()
{
"1",
"2",
"3",
"4",
"5",
"6",
};
//分成3组
var result = RandomizedGroupingArray(list,3);
int groupIndex = 1;
foreach (var item in result)
{
Console.WriteLine($"第{groupIndex}组");
foreach (var item2 in item)
{
Console.WriteLine(item2);
}
Console.WriteLine();
}
}
/// <summary>
/// 随机分组
/// </summary>
/// <param name="list">列表集合</param>
/// <param name="GroupCount">组数</param>
/// <returns></returns>
public static List<List<string>> RandomizedGroupingArray(List<string> list, int GroupCount = 1)
{
//打乱
Random random = new Random();
list = list.OrderBy(x => random.Next()).ToList();
//分组
var groups = list
.Select((item, index) => new { Item = item, GroupIndex = index % GroupCount })
.GroupBy(item => item.GroupIndex, (key, group) => group.Select(groupItem => groupItem.Item).ToList())
.ToList();
return groups;
}
}
}
标签:ToList,C#,List,list,var,item,分组,集合
From: https://www.cnblogs.com/cqpanda/p/17013549.html