从List中获取5个字符串组

时间:2014-12-11 10:06:27

标签: c# .net linq

我有一个List<string>,我想从中获取5个项目组。没有键或任何简单的分组......但它总是5的倍数。

e.g。

{"A","16","49","FRED","AD","17","17","17","FRED","8","B","22","22","107","64"}

分组:

"A","16","49","FRED","AD"
"17","17","17","FRED","8"
"B","22","22","107","64"

但我无法找到一种简单的方法来做到这一点!

非常确定可以使用枚举和Take(5)...

来完成

7 个答案:

答案 0 :(得分:7)

 List<List<string>> result = new List<List<string>>();
 for(int i = 0; i < source.Count; i += 5 )
      result.Add(source.Skip(i).Take(5).ToList());

喜欢这个吗?

答案 1 :(得分:7)

您可以使用整数除法技巧:

List<List<string>> groupsOf5 = list
    .Select((str, index) => new { str, index })
    .GroupBy(x => x.index / 5)
    .Select(g => g.Select(x => x.str).ToList())
    .ToList();

答案 2 :(得分:3)

通用编程语法:

     public List<List<string>> Split(List<string> items, int chunkSize = 5)
     {
         int chunkCount = items.Count/chunkSize;
         List<List<string>> result = new List<List<string>>(chunkCount);

         for (int i = 0; i < chunkCount; i++ )
         {
             result.Add(new List<string>(chunkSize));
             for (int j = i * chunkSize; j < (i + 1) * chunkSize; j++)
             {
                 result[i].Add(items[j]);
             }
         }

         return result;
     }

O((N/ChunkSize) x ChunkSize) = O(N),这是线性的。

答案 3 :(得分:2)

我推荐MoreLINQ库中的Batch方法:

var result = list.Batch(5).ToList();

答案 4 :(得分:1)

使用Take()和Skip()来实现此目的:

        List<string> list = new List<string>() { "A", "16", "49", "FRED", "AD", "17", "17", "17", "FRED", "8", "B", "22", "22", "107", "64" };

        List<List<string>> result = new List<List<string>>();
        for (int i = 0; i < list.Count / 5; i++)
        {
            result.Add(list.Skip(i * 5).Take(5).ToList());
        }

答案 5 :(得分:1)

您可以使用此功能:

public IEnumerable<string[]> GetChunk(string[] input, int size)
{
    int i = 0;
    while (input.Length > size * i)
    {
        yield return input.Skip(size * i).Take(size).ToArray();
        i++;
    }
}

它会从你的列表中返回你的块

你可以检查它

var list = new[]
{
    "A", "16", "49", "FRED", "AD", "17", "17", "17", "FRED", "8", "B", "22", "22", "107", "64"
};

foreach (var strings in GetChunk(list, 5))
{
    Console.WriteLine(strings.Length); 
}

答案 6 :(得分:1)

如果您需要性能或无法使用您的.net版本的linq原因,这是一个简单的解决方案O(n)

    private List<List<string>> SplitList(List<string> input, int size = 5)
    {
        var result = new List<List<string>>();
        for (int i = 0; i < input.Count; i++)
        {
            var partResult = new List<string>();
            while (true)
            {
                // save n items
                partResult.Add(input[i]);
                if ((i+1) % size == 0)
                {
                    break;
                }
                i++;
            }
            result.Add(partResult);
        }

        return result;
    }