简体   繁体   中英

Yield return IEnumerable<IEnumerable<…>>

The following code creates an intermediate instance of List<string> and append values to it before yield return it. Is there a good way to avoid creating the instance and yield return the cell values directly?

IEnumerable<IEnumerable<string>> GetStrValues()
{
    ......
        foreach (var r in rows)
        {
            var row = new List<string>();
            foreach (var c in r.Cells())
            {
                var value = getCellStr(c);
                row.Add(value);
            }
            yield return row;
        }
    }
}

To avoid creating the list, you can use LINQ:

IEnumerable<IEnumerable<string>> GetStrValues()
{
     return rows.Select(r => r.Cells().Select(getCellStr));
}

This will execute lazily, ie no intermediate list will be created. It's a neat way to avoid allocating memory you won't be needing (unless you are going to iterate several times over the inner IEnumerable<string> , and getCellStr is expensive).

You can get deffered action per cell by using two functions.

IEnumerable<IEnumerable<string>> GetStrValues()
{
    ......
        foreach (var r in rows)
        {
            yield return GetCellValues(row);
        }
    }
}

IEnumerable<string> GetCellValues(Row r)
{
    foreach (var c in r.Cells())
    {
        yield return getCellStr(c);
    }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM