在C#中,可以使用LINQ(Language Integrated Query)来根据一些标准将List<T>
分组到List<List<T>>
中。下面是一个示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int groupSize = 3; // 每组的大小
List<List<int>> groupedNumbers = numbers
.Select((number, index) => new { number, index }) // 将每个元素与索引关联起来
.GroupBy(x => x.index / groupSize) // 根据索引进行分组
.Select(group => group.Select(x => x.number).ToList()) // 将每个分组中的元素提取出来并转换为List
.ToList(); // 将分组结果转换为List<List<int>>
foreach (List<int> group in groupedNumbers)
{
Console.WriteLine(string.Join(", ", group));
}
}
}
上述代码中,我们首先创建了一个包含整数的List<int>
,然后定义了每个分组的大小groupSize
为3。接下来,使用LINQ的Select
方法将每个元素与索引关联起来,并使用GroupBy
方法根据索引进行分组。最后,使用Select
方法将每个分组中的元素提取出来并转换为List<int>
,最终使用ToList
方法将分组结果转换为List<List<int>>
。
以上代码的输出结果为:
1, 2, 3
4, 5, 6
7, 8, 9
10
这样就根据C#中的一些标准将List<T>
分组到List<List<T>>
中了。
腾讯云相关产品和产品介绍链接地址:
请注意,以上仅为腾讯云的一些相关产品和服务,其他云计算品牌商也提供类似的产品和服务。
没有搜到相关的结果
领取专属 10元无门槛券
手把手带您无忧上云