Using foreach loop with collections in C#

I have following  code that is trying to retrieve all the Items(collection) and their corresponding Sub items  in C# and it's working fine without any issue.

public ObservableCollection<DemoViewModel> Items { get; private set; }

foreach (var demoviewmodelitem in DemoViewModel.Items) //Items collection (Count=8)
     foreach (var item in demoviewmodelitem.SubItems)


Open in new window

For the new requirement I don't need all the Items (collection) and their corresponding subitems in the above code instead I  just need to retrieve the Selected Item in UI and the corresponding subitems.So my team has changed the code in the viewModel class by adding a property "selectedItem" that contains item selected by the user.

When I debug the above code in the Add Watch I can see DemoViewModel.selectedItem contains selected item (for instance Item6) by the user in UI and the corresponding subitems.

So I have changed the outer foreach loop from

foreach (var demoviewmodelitem in DemoViewModel.Items) //Items collection


foreach (var demoviewmodelitem in DemoViewModel.selectedItem) //selectedItem Property

Open in new window

and getting following error. How to avoid this error?

Error: foreach statement cannot operate on variables of type "class name XXXXXXXXX" does not contain a public definition for 'GetEnumerator'

Thanks in Advance
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
You can't foreach over something that is not a collection. DemoViewModel.selectedItem is not a collection, it's simply an object. Just use that reference by itself and nix the foreach.


var demoviewmodelitem = DemoViewModel.selectedItem;

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Meir RivkinFull stack Software EngineerCommented:
foreach (var demoviewmodelitem in DemoViewModel.selectedItem.SubItems) 

Open in new window

ksd123Author Commented:
Thank you
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.