c# - Simplify double foreach instruction -


i need browse word document , retrieve text boxes in order modify them.

but need count them before, , think wrote inefficient.

i'd know if it's possible simplify following:

foreach (microsoft.office.interop.word.headerfooter oheader in documentold.sections[1].headers) {     foreach (microsoft.office.interop.word.shape shape in oheader.shapes)     {         if (shape.name.contains("text box"))         {             listtextbox.add(new keyvaluepair<string, string>(shape.name.tostring(), shape.textframe.textrange.text.tostring()));         }     } }  int count = listtextbox.count(); 

i want know how many elements contain "text box" in shapes.

i see 2 ways can this.

using linq syntax:

var count = (   oheader in documentold.sections[1].headers   shape in oheader.shapes   shape.name.contains("text box")).count(); 

or, using ienumerable extension methods:

var count = documentold.sections[1].headers               .selectmany(h => h.shapes)               .count(s => s.name.contains("text box")); 

note version inefficient in creates list , keyvaluepairs needlessly, given want count number of shapes match condition. other that, nested foreach blocks fine performance, may lack in readability versus linq equivalents.

also, please note have not tested code above.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -