-5

I like to split the list in to multiple list, list contains GUID's. For an example, if main list contains 130 GUID's, I have kept threshold as 50, so it should return, 3 list, 1st and 2nd list should contain 50 list each and third list will have 30 GUID's.

How can we do it? Please help me out!!

  • 1
    I highly recommend you search the site before posting questions. The related list of questions for this question shows many duplicates. – Daniel Kelley Oct 09 '15 at 09:25

3 Answers3

1

You can use this code. here I'm using string for demo, you can use your guid.

var list = new List<string> { "a", "b", "c", "d", "e" };
var threashold = 2;
var total = list.Count();

var taken = 0;
var sublists = new List<List<string>>(); //your final result
while (taken < total)
{
    var sublst = list.Skip(taken)
        .Take(taken + threashold > total ? total - taken : threashold)
        .ToList();
    taken += threashold;
    sublists.Add(sublst);
}
Arghya C
  • 9,805
  • 2
  • 47
  • 66
0

You can use following LINQ query:

 // your sample list
 List<Guid> guids = Enumerable.Range(0, 130).Select(i => Guid.NewGuid()).ToList();

 List<List<Guid>> splitted = guids
    .Select((guid, index) => new { guid, index })
    .GroupBy(x => x.index / 50)
    .Select(g => g.Select(x => x.guid).ToList())
    .ToList();

The essential method is Enumerable.GroupBy which groups them by index / 50. because integer division truncates the fractional part you get groups of 50.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thanks Tim, It's working, Appreciated but Another way to do is, it may be helpful, using MoreLinq ... IEnumerable> result = enumerableGuids.Batch(50); – mariapradeep Oct 19 '15 at 12:37
0

You can use MoreLinq written by Jon Skeet: google code (available on nuget)

The method you are looking for is Batch:

using MoreLinq
...
IEnumerable<IEnumerable<Guid>> result = enumerableGuids.Batch(50);
pwas
  • 3,225
  • 18
  • 40
  • Hi, It's a perfect way to use it, I have downloaded MoreLinq via Nuget and it works like a charm!!! Thanks much, Appreciated.. – mariapradeep Oct 19 '15 at 12:36