开发者

Custom iterator for dictionary?

开发者 https://www.devze.com 2022-12-27 12:02 出处:网络
in my C#-Application, I have a Dictionary object. When iterating over the ob开发者_开发知识库ject using foreach, I naturally get each element of the dictionary. But I want only certain elements to be

in my C#-Application, I have a Dictionary object. When iterating over the ob开发者_开发知识库ject using foreach, I naturally get each element of the dictionary. But I want only certain elements to be iterated, depending on the value of a property of MyValue.

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

Whenever AmIIncludedInTheIteration is false, the item shall not be returned by foreach. I understand that I need to implement my own iterator and override the Dictionary-Iterator somewhere. Can anyone here give me a short HowTo?

Thanks in advance, Frank


In C#3 and above you can use a (LINQ) extension method:

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

foreach (var x in myFilteredCollection ) ...


You have to implement your own IEnumerator and then you can control what is returned in the MoveNext function.

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

This should given you a number of pages in which to start from.


I assume you want to iterate over the values in your dictionary, you can use a linq method for this:

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

}


Or you filter it when iterating the dictionary:

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

Just an idea...

0

精彩评论

暂无评论...
验证码 换一张
取 消