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

时间:2016-03-16 13:15:41

标签: c# ienumerable

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

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

在课程StructuredTable内。我希望能够编写一个循环

StructuredTable  table = new StructuredTable();

// Fill the table with values

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

其中在列数和行数的最大值范围内的任何x,y组合都返回为null。我无法找到以这种方式使用yield的示例。

2 个答案:

答案 0 :(得分:1)

这样的东西
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;
            }
        }
}

答案 1 :(得分:1)

基于键合小的事实,您可以在此处进行大量优化。

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-&gt; Value字典,其中

  

key = hash(keyOne,keyTwo)

你不需要任何花哨的懒惰结构(产量),因为你已经有了可用的值。