Skip to content

Worksheet Enumerator does not behave as expected #1829

Closed
@OssianEPPlus

Description

@OssianEPPlus

You can currently delete worksheets while iterating through the same worksheets. This causes issues as the worksheet originally at index [1] gets locked to index 0.

Per standard iteration of e.g. List we should throw if the collection is changed while iterating through it.
We should also add a RemoveAll() function to Worksheets with a predicate similar to List

[TestMethod]
public void DeletingWorksheetsWithParameters()
{
    using (var p = OpenPackage("DeletingGroupOfWorksheets.xlsx"))
    {
        var wb = p.Workbook;
        var worksheets = wb.Worksheets;

        for (int i = 0; i < 5; i++)
        {
            worksheets.Add($"Data {i}");
        }

        for (int i = 0; i < 5; i++)
        {
            worksheets.Add($"SomeWorksheet{i}");
        }

        //Deleting worksheets with foreach
        //Skips over index[1]
        //Should probably throw as the enumerator changes while in it
        foreach (var ws in p.Workbook.Worksheets)
        {
            if (ws.Name.StartsWith("Data ", StringComparison.OrdinalIgnoreCase))
            {
                p.Workbook.Worksheets.Delete(ws);
            }
        }

        var countWs = p.Workbook.Worksheets.Count();

        Assert.AreEqual(countWs , 5);
    }

Worksheets.Delete() on RemoveAndShift appears to cause the skipping.

Ideally users should be able to do something like Remove all or Delete all :

p.Workbook.Worksheets.RemoveAll(x => x.Name.StartsWith("Data "));

Metadata

Metadata

Labels

bugSomething isn't workingenhancementNew feature or request

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions