C# - 分区列表中优雅的方式? [英] C# - elegant way of partitioning a list?

查看:206
本文介绍了C# - 分区列表中优雅的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过指定每个分区的元素的数目的列表划分成列表的列表,

I'd like to partition a list into a list of lists, by specifying the number of elements in each partition.

举例来说,假设我有列表{1,2,... 11},并想对它进行分区,这样每组有4个元素,最后一组填充尽可能多的元素,因为它可以。由此产生的分区看起来像{{1..4} {5..8} {9..11}}

For instance, suppose I have the list {1, 2, ... 11}, and would like to partition it such that each set has 4 elements, with the last set filling as many elements as it can. The resulting partition would look like {{1..4}, {5..8}, {9..11}}

什么是写这个的一个优雅的方式?

What would be an elegant way of writing this?

推荐答案

下面是一个扩展方法,将你想要做什么:

Here is an extension method that will do what you want:

public static IEnumerable<List<T>> Partition<T>(this IList<T> source, Int32 size)
{
	for (int i = 0; i < (source.Count / size) + (source.Count % size > 0 ? 1 : 0); i++)
		yield return new List<T>(source.Skip(size * i).Take(size));
}

编辑:下面是函数的一个更清洁的版本:

Here is a much cleaner version of the function:

public static IEnumerable<List<T>> Partition<T>(this IList<T> source, Int32 size)
{
	for (int i = 0; i < Math.Ceiling(source.Count / (Double)size); i++)
		yield return new List<T>(source.Skip(size * i).Take(size));
}

这篇关于C# - 分区列表中优雅的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆