Take groups of 5 lines from the list

I have a List<string> , and I want to take groups of 5 elements from it. There are no keys or anything simple to group ... but it will always be a multiple of 5.

eg.

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

Take the groups:

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

but I canโ€™t decide an easy way to do it!

Pretty sure that this can be done with an enum and Take (5) ...

+5
source share
7 answers

You can use the whole division trick:

 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(); 
+7
source
  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()); 

Like this?

+7
source

In general programming syntax:

  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; } 

It O((N/ChunkSize) x ChunkSize) = O(N) , which is linear.

+3
source

I recommend the Batch method from the MoreLINQ library:

 var result = list.Batch(5).ToList(); 
+2
source

Use Take () and Skip () to achieve this:

  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()); } 
+1
source

You can use this function:

 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++; } } 

he returns you pieces from your list

you can check it like

 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); } 
+1
source

If you need performance or you cannot use the LINK reason for your .net version, this is a simple solution with 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; } 
+1
source

Source: https://habr.com/ru/post/1208797/


All Articles