Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through items of CompositeCollection

Consider the code:

ObservableCollection<string> cities = new ObservableCollection<string>();
ObservableCollection<string> states = new ObservableCollection<string>();

ListBox list;

cities.Add("Frederick");
cities.Add("Germantown");
cities.Add("Arlington");
cities.Add("Burbank");
cities.Add("Newton");
cities.Add("Watertown");
cities.Add("Pasadena");

states.Add("Maryland");
states.Add("Virginia");
states.Add("California");
states.Add("Nevada");
states.Add("Ohio");

CompositeCollection cmpc = new CompositeCollection();
CollectionContainer cc1 = new CollectionContainer();
CollectionContainer cc2 = new CollectionContainer();

cc1.Collection = cities;
cc2.Collection = states;

cmpc.Add(cc1);
cmpc.Add(cc2);

list.ItemsSource = cmpc;

foreach(var itm in cmpc)
{
    // itm is CollectionContainer and there are only two itm’s
    // I need the strings
}

While list shows the right data on the GUI

I need this data (without referring to the ListBox) and I am not getting it

like image 979
Dudu Avatar asked Jun 09 '10 09:06

Dudu


3 Answers

Try this: foreach (var itm in cmpc.Cast<CollectionContainer>().SelectMany(x => x.Collection.Cast<string>()))

like image 185
Stephen Cleary Avatar answered Nov 15 '22 06:11

Stephen Cleary


The ListBox uses for its ItemsSource Property the default view of the collection, which you can use, too:

  foreach (string itm in CollectionViewSource.GetDefaultView(cmpc))
  {
    Debug.Print(itm);
  }

You can use the ICollectionView classes to sort or filter an ItemsSource, but be careful while this won't work properly with CompositeCollections, as you can see this question: How to handle a CompositeCollection with CollectionView features?

like image 21
Herm Avatar answered Nov 15 '22 05:11

Herm


you should extract data from cmpc items and set them as data source as list.ItemsSource won't understand that u need to set inner items of items as a datasource
EDIT

You can use this method

List<string> GetData(CompositeCollection cmpc)
        {
            List<string> allStrings = new List<string>();
            foreach (var item in cmpc)
            {
                allStrings.AddRange(item.OfType<string>());
            }
            return allStrings;
        }

and set datasource

list.ItemsSource = GetData(cmpc);
like image 32
Amr Badawy Avatar answered Nov 15 '22 07:11

Amr Badawy