如何枚举一个 HashSet?

6

我有一个定义如下的对象:

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

    public string Answer { get; set; }
}

我需要检查对象problem中的每个问题并操纵一些数据。以下是我的尝试:

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

但是这并不起作用。我收到一个错误消息,上面写着:

严重性 代码 描述 项目 文件 行 错误 CS1579 因为“Entities.Models.Core.Problem”不包含公共定义的“GetEnumerator”,所以foreach语句不能对类型为“Entities.Models.Core.Problem”的变量进行操作

我能否使用其他方法来解决这个问题?请注意,我使用new HashSet<Question>的原因是因为我被告知这是处理唯一问题的方法。

1个回答

17
你需要指定你想要迭代的是包含在Problem中的HashSet,而不是Problem本身:
你需要明确指定要遍历的是Problem中包含的HashSet,而不是Problem本身:
foreach (Question question in problem.Questions) {
    ...
}

由于HashSet的特性,问题可能会以任何顺序出现。如果您想为问题保持特定的顺序,应该使用List。的确,HashSet的元素是唯一的,但这并不意味着如果您的元素是唯一的,就必须使用HashSet


3
只是一点提醒,使用SortedSet可以保持特定的排序顺序。 - Icaro Mota

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接