user1679941
user1679941

Reputation:

How can I enumerate through a HashSet?

I have an object defined like this:

public class Problem
{
    public Problem()
    {
        this.Questions = new HashSet<Question>();
    }

    public string Answer { get; set; }
}

I need to check each of the Questions in the object problem and manipulate some data. Here's what I have tried:

foreach (Question question in problem)
{
    if (question.AssignedTo == null)
    {
        question.QuestionStatusId = 6;
    }
    else
    {
        question.AssignedDate = DateTime.UtcNow;
        question.QuestionStatusId = 5;
    }
}

But this does not work. I get an error message saying:

Severity Code Description Project File Line Error CS1579 foreach statement cannot operate on variables of type 'Entities.Models.Core.Problem' because 'Entities.Models.Core.Problem' does not contain a public definition for 'GetEnumerator'

Is there another way that I can do this? Note that the reason I used new HashSet<Question> was because I was told this is the way to do this if there are unique questions.

Upvotes: 9

Views: 31362

Answers (1)

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 38010

You need to specify that you want to iterate over the HashSet that is contained in the Problem, not the Problem itself:

foreach (Question question in problem.Questions) {
    ...
}

Due to the nature of the HashSet, though, the questions might come out in any order. If you want to maintain a particular order for the questions, you should use a List. It is true that the elements of a HashSet are unique, but that doesn't mean that you have to use a HashSet if your elements are unique.

Upvotes: 20

Related Questions