2

I'm sending SMSs in a batch of 20, so when I extract from my context/db all the SMSs that need sending I'd like to save them in a List of Lists of 20 SMS, like thisList<List<SMS>>.

I'm currently doing it with a for loop but was wondering if there is a way to do it with a single Lambda, that I can't think of?

  • 1
    Hi! Great question. What you are looking for is how to "chunk" an IEnumerable. There's nothing built-in in the .NET framework, but it's not hard to implement. Since we already have a question for that, I have marked your question as a duplicate of that other question. – Heinzi Jul 17 '18 at 08:13
  • Something like this don't work .Select? IEnumerable list = _dbContext.Sms.Where("Put there the condition").ToList(); – Jordi Jordi Jul 17 '18 at 08:43
  • 1
    @Heinzi there actually is something built into the .NET framework for this. `Partitioner.Create(smsList)` and `partitioner.GetPartitions(Math.Ceiling(smsList.Count / 20.0))` – p3tch Jul 17 '18 at 08:46
  • @p3tch: Nice, I did not know that! – Heinzi Jul 17 '18 at 08:55
  • @Heinzi after some testing, the LINQ solution is a lot faster in terms of creating a `List>`. The partitioner might be better if you wanted to enumerate across each chunk on multiple threads via a `Parallel.ForEach` loop or something (rather than creating a collection of chunks to enumerate over later) – p3tch Jul 17 '18 at 09:27

0 Answers0