11

我有一个这样的单维集合:

[1,2,4,5.....n]

我想将该集合转换为这样的二维集合:

[[1,2,3],
[4,5,6],
...]

基本上我想分组或拆分,如果你愿意,数组中的'n'个成员组

我可以用一个foreach语句来做到这一点,但我目前正在学习 LINQ,所以我不想遍历所有元素并手动创建一个新数组,我想使用 LINQ 功能(如果适用)

是否有任何 LINQ 函数可以帮助我完成此任务?

我在想,GroupBy或者SelectMany我不知道他们是否会帮助我,但他们可能会

任何帮助将不胜感激=):**

4

7 回答 7

18

您可以按索引除以批量大小进行分组,如下所示:

var batchSize = 3;
var batched = orig
    .Select((Value, Index) => new {Value, Index})
    .GroupBy(p => p.Index/batchSize)
    .Select(g => g.Select(p => p.Value).ToList());
于 2012-05-31T03:31:00.677 回答
5

使用MoreLinq .Batch

 var result = inputArray.Batch(n); // n -> batch size

例子

    var inputs = Enumerable.Range(1,10);

    var output = inputs.Batch(3);


    var outputAsArray = inputs.Batch(3).Select(x=>x.ToArray()).ToArray(); //If require as array
于 2012-05-31T03:19:39.740 回答
3

你想要Take()Skip()。这些方法可以让你拆分一个IEnumerable. 然后,您可以Concat()再次将它们拍打在一起。

于 2012-05-31T03:18:42.627 回答
2

它不是纯粹的 LINQ,但它打算与它一起使用:

public static class MyEnumerableExtensions
{
    public static IEnumerable<T[]> Split<T>(this IEnumerable<T> source, int size)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source can't be null.");
        }

        if (size == 0)
        {
            throw new ArgumentOutOfRangeException("Chunk size can't be 0.");
        }

        List<T> result = new List<T>(size);
        foreach (T x in source)
        {
            result.Add(x);
            if (result.Count == size)
            {
                yield return result.ToArray();
                result = new List<T>(size);
            }
        }
    }
}

它可以从您的代码中用作:

private void Test()
{
    // Here's your original sequence
    IEnumerable<int> seq = new[] { 1, 2, 3, 4, 5, 6 };

    // Here's the result of splitting into chunks of some length 
    // (here's the chunks length equals 3). 
    // You can manipulate with this sequence further, 
    // like filtering or joining e.t.c.
    var splitted = seq.Split(3);
}
于 2012-05-31T03:19:04.170 回答
2

下面的示例将一个数组拆分为每组 4 个项目。

int[] items = Enumerable.Range(1, 20).ToArray(); // Generate a test array to split
int[][] groupedItems = items
                         .Select((item, index) => index % 4 == 0 ? items.Skip(index).Take(4).ToArray() : null)
                         .Where(group => group != null)
                         .ToArray();
于 2012-05-31T03:42:18.660 回答
1

它很简单:

static class LinqExtensions
{
    public static IEnumerable<IEnumerable<T>> ToPages<T>(this IEnumerable<T> elements, int pageSize)
    {
        if (elements == null)
            throw new ArgumentNullException("elements");
        if (pageSize <= 0)
            throw new ArgumentOutOfRangeException("pageSize","Must be greater than 0!");

        int i = 0;
        var paged = elements.GroupBy(p => i++ / pageSize);
        return paged;
    }
}
于 2016-09-13T13:43:14.687 回答
0

我基于Jeremy Holovacs 的答案的解决方案,并使用 Take() 和 Skip() 创建子数组。

        const int batchSize = 3;
        int[] array = new int[] { 1,2,4,5.....n};

        var subArrays = from index in Enumerable.Range(0, array.Length / batchSize + 1)
                      select array.Skip(index * batchSize).Take(batchSize);
于 2020-01-11T15:53:05.907 回答