• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 468
  • Last Modified:

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
1 Solution
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

Meir RivkinFull stack Software EngineerCommented:
foreach (var demoviewmodelitem in DemoViewModel.selectedItem.SubItems) 

Open in new window

ksd123Author Commented:
Thank you
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now