views:

74

answers:

4

Hi folks,

in my C#-Application, I have a Dictionary object. When iterating over the object 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

A: 

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.

JDMX
Posting google searches is not encouraged here. If you have an answer, answer the question, if you don't don't.
Oded
+2  A: 

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

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

foreach (var x in myFilteredCollection ) ...
Henk Holterman
A: 

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 ))
{

}
Luis
A: 

Or you filter it when iterating the dictionary:

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

Just an idea...

Stefan Steinegger