tags:

views:

547

answers:

2

Is it possible to itterate directly over properties of the objects stored within a Dictionary collection in C#?

For example, I have a Dictionary called Fields of type Dictionary<String, Field>. The Field object has a property of Data which is of type XmlDataDocument so I would like to do something like,

foreach(XmlDataDocument fieldData in Fields.Values.Data){

}

I know it's pretty trivial since all I would need to do when itterating over Field objects instead would be,

XmlDataDocument fieldData = field.Data;

within the Field itteration however if there is a quicker way to do it I'd like to know :-)

+1  A: 

yes, create a custom collection based on Dictionary and then add your own iterator to it...

   public class MyFieldCollection: Dictionary<string, Field>
   {
       public IEnumerable<XmlDataDocument> Data
       {
           foreach(Field f in this.Values)
              yield return f.Data;
       }
   }

Then in client code all you need to do is

  MyFieldCollection MFC = new MyFieldCollection();    
   foreach (XmlDataDocument doc in MFC.Data)
   {
       // DoWhatever (doc ); 
   }
Charles Bretana
+5  A: 

In C# 3.0:

foreach (var data in Fields.Values.Select(x => x.Data))
{
}

It's not any "quicker" though.

Barry Kelly
beat me by 10 seconds :D
Stan R.