Search code examples
c#excelforeachopenxmlopenxml-sdk

Foreach loop using Regex to find XML pattern


I've created a regex pattern which finds all #REF in my excel file. I've created a foreach loop to return all the #REF and siplay them in the console along with a count of them. This works fine. However I then created a foreach loop to remove all the #REF references but it only removes one each time I run the project. I've debugged this and after Regex finds the match once in the if statement the next time it enters into the foreach it skips the if statement as if it can't find another match. I'm not sure why this is

My code is as fallows

Code to return all the #ref values

        using (var spreadsheet = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(@"C:\Users\Craig\Desktop\newTest.xlsx", true))
        {

            var workbook = spreadsheet.WorkbookPart;
            Workbook w = new Workbook();
            var names = workbook.Workbook.DefinedNames;
            var work = workbook.Workbook;






            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"#REF");

            int count = result.InactiveNamedRangeCount = names.Count(n => regex.IsMatch(n.InnerText));
            Console.WriteLine(count);
            foreach (var name in names)
            {
                if (regex.IsMatch(name.InnerText))
                {
                    Console.WriteLine(name.InnerText);
                }
            }

Code to delete each #REF value

            foreach (var name in names)
            {

                if (regex.IsMatch(name.InnerText))
                {
                    name.Remove();
                    work.Save();

                }
            }


            Console.WriteLine(count);

            Console.ReadKey();
        }

Solution

  • The solution to the problem was I needed to add a ToList to my names variable.

    foreach (var name in names.ToList())
                {
    
                    if (regex.IsMatch(name.InnerText))
                    {
                        name.Remove();
                        work.Save();
    
                    }
                }