使用LINQ将列表转换为列表列表 [英] Use LINQ to Convert a List to a List of Lists
问题描述
我有一个值列表:
IList<V> values = { V1, V2, V3, V4, V5, V6, V7 };
我想将列表转换为列表列表,其中每个子列表都是指定的大小.每个子列表的大小可能会有所不同.例如:
I would like to convert the list into a list of lists, where each sub-list is a specified size. The size of each sub-list could vary. For example:
IList<IList<V>> values_size2 = { { V1, V2 }, { V3, V4 }, { V5, V6 }, { V7 } };
IList<IList<V>> values_size3 = { { V1, V2, V3 }, { V4, V5, V6 }, { V7 } };
IList<IList<V>> values_size4 = { { V1, V2, V3, V4 }, { V5, V6, V7 } };
我可以使用嵌套循环很容易地做到这一点,但是想知道是否有使用LINQ的聪明方法呢?
I could probably do this pretty easily using nested loops, but was wondering if there was a clever way to do this using LINQ?
我最初的想法是使用 Aggregate 某种方法,但马上什么也没想到.
My initial thought would be to use the Aggregate method somehow, but nothing comes to mind right away.
谢谢.
推荐答案
这是基于IEnumerable
的通用Batch
函数.您可以将返回类型从IEnumerable<IEnumerable<T>>
更改为IEnumerable<IList<T>>
,而无需进行其他更改(因为在我的实现中,它已经是列表了.要更改整个内容以返回列表的列表,您需要调用`ToList on结果,或者进行更复杂的重构.
Here is a generic IEnumerable
based Batch
function. You can just change the return type from IEnumerable<IEnumerable<T>>
to IEnumerable<IList<T>>
with no other changes (since in my implementation it's already a list. To change the whole thing to return a list of lists you'd need to either call `ToList on the result, or make a more involved refactor.
请注意,从技术上讲,这不是使用LINQ,而只是创建一种使用与LINQ相同的样式和模式的新方法.
Note that technically this isn't using LINQ, it's just creating a new method that uses the same style and patterns commonly used by LINQ.
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source
, int batchSize)
{
//TODO validate parameters
List<T> buffer = new List<T>();
foreach (T item in source)
{
buffer.Add(item);
if (buffer.Count >= batchSize)
{
yield return buffer;
buffer = new List<T>();
}
}
if (buffer.Count >= 0)
{
yield return buffer;
}
}
这篇关于使用LINQ将列表转换为列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!