我希望将一个列表按照指定的元素数量划分成多个子列表。
例如,假设我有列表 {1, 2, ... 11},希望将其划分为每个子列表包含4个元素,并且最后一个子列表包含尽可能多的元素。则得到的子列表应该是 {{1..4}, {5..8}, {9..11}}。
有什么优雅的方法可以实现这个功能呢?
我希望将一个列表按照指定的元素数量划分成多个子列表。
例如,假设我有列表 {1, 2, ... 11},希望将其划分为每个子列表包含4个元素,并且最后一个子列表包含尽可能多的元素。则得到的子列表应该是 {{1..4}, {5..8}, {9..11}}。
有什么优雅的方法可以实现这个功能呢?
这里是一个扩展方法,可以实现你想要的功能:
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));
}
编辑: 这是函数的更加简洁版本:
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));
}
Skip
和 Take
只是在给定序列上进行循环,如果源代码实现了 IList
接口并且可以通过索引访问,则不会进行检查/优化。因此它们的时间复杂度为 O(m)
(其中 m
是要跳过或取出的元素数量)。因此,这个 Partition()
扩展方法可能无法提供预期的性能。 - tigrou.ToList()
方法来获取一个可索引的列表。 - mklement0使用LINQ,您可以在一行代码中将您的组划分如下...
var x = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
var groups = x.Select((i, index) => new
{
i,
index
}).GroupBy(group => group.index / 4, element => element.i);
你可以像下面这样遍历这些组...
foreach (var group in groups)
{
Console.WriteLine("Group: {0}", group.Key);
foreach (var item in group)
{
Console.WriteLine("\tValue: {0}", item);
}
}
然后你将会获得类似这样的输出...
Group: 0
Value: 1
Value: 2
Value: 3
Value: 4
Group: 1
Value: 5
Value: 6
Value: 7
Value: 8
Group: 2
Value: 9
Value: 10
Value: 11
某些代码(未经测试):
IEnumerable<IList<T>> PartitionList<T>(IList<T> list, int maxCount)
{
List<T> partialList = new List<T>(maxCount);
foreach(T item in list)
{
if (partialList.Count == maxCount)
{
yield return partialList;
partialList = new List<T>(maxCount);
}
partialList.Add(item);
}
if (partialList.Count > 0) yield return partialList;
}
IList<IList<T>> listOfLists = new List<T>(PartitionList<T>(list, maxCount));
PartitionList(list, enablePartition ? 500 : int.MaxValue)
)。一个可能的改进是仅在源实现ICollection时设置列表容量,并将maxCount夹紧到集合内元素的数量。 - tigrouIEnumerable<IEnumerable<T>> PartitionEnumeration<T> (IEnumerable<T> enumeration, int maxCount)
,可以轻松实现而不需要分配列表。 - JoeIEnumerable<IEnumerable<T>>
并依赖于一个从不分配任何东西的实现(例如:它只从源中产生元素),那么如果结果不是按顺序枚举的(例如:在枚举分区 2 之前枚举分区 4 或某些分区仅被部分枚举),你将会遇到麻烦。我认为使用列表更安全。 - tigroupublic static IEnumerable<IList<T>> Partition<T>(
this IEnumerable<T> source,
int size)
{
if (size < 2)
{
throw new ArgumentOutOfRangeException(
nameof(size),
size,
"Must be greater or equal to 2.");
}
T[] partition;
int count;
using (var e = source.GetEnumerator())
{
if (e.MoveNext())
{
partition = new T[size];
partition[0] = e.Current;
count = 1;
}
else
{
yield break;
}
while(e.MoveNext())
{
partition[count] = e.Current;
count++;
if (count == size)
{
yield return partition;
count = 0;
partition = new T[size];
}
}
}
if (count > 0)
{
Array.Resize(ref partition, count);
yield return partition;
}
}
1
处使用 ArgumentOutOfRangeException
?你可以把它改成 size < 1
,然后在 if (e.MoveNext()
块中分配给 partition[0]
后添加 if (size == 1) yield return partition; else count = 1;
。 - Brett Caswellpublic static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> list, int size)
{
while (list.Any()) { yield return list.Take(size); list = list.Skip(size); }
}
对于字符串的特殊情况
public static IEnumerable<string> Partition(this string str, int size)
{
return str.Partition<char>(size).Select(AsString);
}
public static string AsString(this IEnumerable<char> charList)
{
return new string(charList.ToArray());
}
var yourList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
var groupSize = 4;
// here's the actual query that does the grouping...
var query = yourList
.Select((x, i) => new { x, i })
.GroupBy(i => i.i / groupSize, x => x.x);
// and here's a quick test to ensure that it worked properly...
foreach (var group in query)
{
foreach (var item in group)
{
Console.Write(item + ",");
}
Console.WriteLine();
}
List<List<T>>
而不是一个 IEnumerable<IEnumerable<T>>
,那么请按以下方式更改查询:var query = yourList
.Select((x, i) => new { x, i })
.GroupBy(i => i.i / groupSize, x => x.x)
.Select(g => g.ToList())
.ToList();
或者在 .Net 2.0 中,你可以这样做:
static void Main(string[] args)
{
int[] values = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
List<int[]> items = new List<int[]>(SplitArray(values, 4));
}
static IEnumerable<T[]> SplitArray<T>(T[] items, int size)
{
for (int index = 0; index < items.Length; index += size)
{
int remains = Math.Min(size, items.Length-index);
T[] segment = new T[remains];
Array.Copy(items, index, segment, 0, remains);
yield return segment;
}
}
var list = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; //Added 0 in front on purpose in order to enhance simplicity.
int[] array = list.ToArray();
int step = 4;
List<int[]> listSegments = new List<int[]>();
for(int i = 0; i < array.Length; i+=step)
{
int[] segment = new ArraySegment<int>(array, i, step).ToArray();
listSegments.Add(segment);
}
public static IList<HashSet<T>> Partition<T>(this IEnumerable<T> input, Func<T, object> partitionFunc)
{
Dictionary<object, HashSet> partitions = new Dictionary<object, HashSet<T>>();
object currentKey = null;
foreach (T item in input ?? Enumerable.Empty<T>())
{
currentKey = partitionFunc(item);
if (!partitions.ContainsKey(currentKey))
{
partitions[currentKey] = new HashSet<T>();
}
partitions[currentKey].Add(item);
}
return partitions.Values.ToList();
}