0

I have documents that are generated with OpenXML. I am working on reducing the amount of code required to generate the document.

I have a document section that has 7 paragraphs in it. Currently I insert them with:

var paragraph = new Paragraph {};
body.Append(paragraph);` 

So my question is, is there a better way to insert multiple paragraphs without inserting the above code 7 times?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
kelz1004
  • 11
  • 3

1 Answers1

0

You don't need to copy the code 7 times. You can do this instead:

foreach (var i in Enumerable.Range(0, 7))
    body.Append(new Paragraph());

Or if you are worried about performance, just use a for loop:

for (var i = 0; i < 7; i++)
    body.Append(new Paragraph());

Also see this other Stack Overflow answer: Is there a shorter/simpler version of the for loop to anything x times?

Community
  • 1
  • 1
Botond Balázs
  • 2,512
  • 1
  • 24
  • 34
  • 3
    This is unnecessary. Use a standard for loop. You're allocating an enumerator for no good reason – pinkfloydx33 Nov 22 '16 at 00:49
  • If everybody thought like that, we would all still program in Assembly. This is much more readable than a standard for loop. I would only optimize it if it turned out to be a performance bottleneck. Look at the second and third most popular answers here: http://stackoverflow.com/questions/3932413/is-there-a-shorter-simpler-version-of-the-for-loop-to-anything-x-times – Botond Balázs Nov 22 '16 at 02:05
  • 2
    Completely out of context of the question :) But I don't where using the Range method enhances readability. In the other hand, the performance impact is non-significant on small loops. Maybe Microsoft should implement something like `for(var i = 0 to 7)` if readbility was actually an issue. – Steve B Nov 22 '16 at 10:00
  • @SteveB If you have a lot of for loops like that, the code quickly becomes hard to read. I think Jon Skeet's `.Times` extension method (the accepted answer to the question I linked) would be the best solution both in terms of readability and performance, but I wanted to use something that is already included in the framework. Also note that the idiomatic python way of doing this is `for _ in range(7): doSomething()`, which is the direct equivalent. I tried to do something like that in C#. – Botond Balázs Nov 22 '16 at 11:30
  • Thanks, I knew I was trying to overthink this! – kelz1004 Nov 22 '16 at 14:45