views:

34

answers:

2

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

+1  A: 

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);
Space Cracker
his is a nice trick.Isnt there a way to do it directly?How come the ListBox sees the strings? What does it use?
Dudu
what did you mean by directly ?
Space Cracker
something on the line of : foreach(var itm in cmpc)
Dudu
that's already what I did in the above code ,I just make your foreach loop extract strings and return it as a datasource for ListBox ... could you please clarify to me what you need exactly ?
Space Cracker
+2  A: 

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

Stephen Cleary
this will iterate for the only first level CollectionContainer that won't get results
Space Cracker
Updated answer to reflect your comment (you were correct).
Stephen Cleary
This is a nice trick.Isnt there a way to do it directly?How come the ListBox sees the strings? What does it use?
Dudu