private IReadOnlyList <IReadOnlyCollection <Message.Attachment> > ChunkAttachmentsOrThrow( IReadOnlyList <Message.Attachment> attachments, int sizeThreshold) { // Splits a list of attachments into "chunks" of at most 8MB each // If any individual attachment is larger than 8MB, will throw an error var chunks = new List <List <Message.Attachment> >(); var list = new List <Message.Attachment>(); // sizeThreshold is in MB (user-readable) var bytesThreshold = sizeThreshold * 1024 * 1024; foreach (var attachment in attachments) { if (attachment.Size >= bytesThreshold) { throw Errors.AttachmentTooLarge(sizeThreshold); } if (list.Sum(a => a.Size) + attachment.Size >= bytesThreshold) { chunks.Add(list); list = new List <Message.Attachment>(); } list.Add(attachment); } if (list.Count > 0) { chunks.Add(list); } return(chunks); }