如何为字典设置迭代器?

时间:2012-01-19 12:30:06

标签: c#

我有一个使用字典存储一些数据的类。

但我想从外部隐藏该实现细节,迭代我想要将迭代器发送到我班级的所有数据

我该怎么做?

4 个答案:

答案 0 :(得分:4)

public IEnumerable<KeyValuePair<int, string>> Foo()
{
    var implementationDetail = new Dictionary<int, string>
    {
        { 1, "foo" },
        { 2, "bar" },
    };

    return implementationDetail;
}

答案 1 :(得分:2)

您可以调用返回枚举数的Dictinary.GetEnumerator()

答案 2 :(得分:1)

您可以返回_dict.getEnumerator(),但会生成KeyValuePair项。您也可以返回IDictionary

所以你可能想要_dict.Keys.getEnumerator(),和/或相同的值。

但是返回一个枚举器很奇怪,更好的回归:_dict.Keys as IEnumerable<KeyType>

答案 3 :(得分:1)

要迭代字典,您可以使用:

返回KeyValuePairs的

Dictionary.GetEnumerator

返回KeyCollection的

Dictionary.Keys

Dictionary.Values返回ValueCollection。

如果由于某种原因需要隐藏字典,可以将Dictionary.Keys和Dictionary.Values转换为数组/列表,无论你想要什么。

相关问题