【问题标题】:Custom iterator for dictionary?字典的自定义迭代器?
【发布时间】:2010-04-21 14:27:24
【问题描述】:

在我的 C#-Application 中,我有一个 Dictionary 对象。当使用 foreach 遍历对象时,我自然会得到字典的每个元素。但我只想迭代某些元素,具体取决于 MyValue 的属性值。

class MyValue
{
  public bool AmIIncludedInTheIteration { get; set; }
  ...
}

只要 AmIIncludedInTheIteration 为 false,foreach 将不会返回该项目。我知道我需要实现自己的迭代器并在某处覆盖 Dictionary-Iterator。这里有人可以给我一个简短的 HowTo 吗?

提前致谢, 弗兰克

【问题讨论】:

  • 你使用的是什么版本的 C#?

标签: c# dictionary iterator


【解决方案1】:

在 C#3 及以上版本中,您可以使用 (LINQ) 扩展方法:

var myFilteredCollection = myCollection.Where( x => x.AmIIncludedInTheIteration );

foreach (var x in myFilteredCollection ) ...

【讨论】:

    【解决方案2】:

    您必须实现自己的 IEnumerator,然后您可以控制 MoveNext 函数中返回的内容。

    谷歌搜索http://www.google.com/search?source=ig&hl=en&rlz=&=&q=dotnet+custom+IEnumerator&aq=f&aqi=&aql=&oq=&gs_rfai=

    这应该为您提供了一些可以从其中开始的页面。

    【讨论】:

    • 这里不鼓励发布谷歌搜索。如果您有答案,请回答问题,如果您没有答案。
    【解决方案3】:

    我假设您想遍历字典中的值,您可以为此使用 linq 方法:

    foreach(MyValue value in MyDictionary.Values.Where(i=>i.AmIIncludedInTheIteration ))
    {
    
    }
    

    【讨论】:

      【解决方案4】:

      或者你在迭代字典时过滤它:

      foreach (KeyValuePair<X, MyValue> element in dict.Where(x => x.Value.AmIIncludedInTheIteration)
      {
        // ...
      }
      

      只是一个想法......

      【讨论】:

        猜你喜欢
        • 2019-06-03
        • 1970-01-01
        • 2013-02-17
        • 2019-04-01
        • 2015-02-04
        • 2016-06-18
        • 2016-04-05
        • 2021-09-15
        相关资源
        最近更新 更多