C# 从嵌套稀疏字典生成 IEnumerable

C# Generate An IEnumerable from Nested Sparse Dictionaries

所以我有一个元素稀疏矩阵,表示为

Dictionary<int, Dictionary<int, StructuredCell>> CellValues = new Dictionary<int, Dictionary<int, StructuredCell>>();

里面一个classStructuredTable。我希望能够编写一个循环

StructuredTable  table = new StructuredTable();

// Fill the table with values

foreach(StructuredCell cell in table.Cells()) {
    // Fill an alternate structure
}

其中最大列数和行数范围内的任何 x,y 组合都返回为 null。我似乎找不到这样使用 yield 的示例。

类似于

public IEnumerable<StructuredCell> Cells(){
    for (int i = 0; i < maxColumn; i++)
        {
            Dictionary<int, StructuredCell> row = null;
            CellValues.TryGetValue(i, out row);
            for (int j = 0; j < maxRow; j++)
            {
                if (row == null) yield return null;
                StructuredCell cell = null;
                row.TryGetValue(j, out cell);
                yield return cell;
            }
        }
}

基于键比较小的事实,你可以在这里做一些优化。

public class DataStructure {
    private const int MAX_VALUE = 100000;
    private readonly Dictionary<long, StructuredCell> CellValues;

    private void Add(int keyOne, int keyTwo, StructuredCell cell) {
        long hashKey = keyOne*MAX_VALUE + keyTwo;

        CellValues[hashKey] = cell;
    }

    private void Remove(int keyOne, int keyTwo)
    {
        long hashKey = keyOne * MAX_VALUE + keyTwo;

        CellValues.Remove(hashKey);
    }

    private IEnumerable<StructuredCell> GetCells() {
        return CellValues.Values;
    }
}

您可以保留一个简单的 Key->Value 字典,其中

key = hash(keyOne, keyTwo)

您不需要任何花哨的惰性构造(收益),因为您已经有了可用的值。