Bogdan Molinger
Bogdan Molinger

Reputation: 341

Foreach in a Hashset

I have a structure which can't contain duplicates, so I've chosen to represent it as a hashset

class Team
{
    private HashSet<HeroStats> team = new HashSet<HeroStats>();

    public int count()
    {
        int res = 0;
        res = team.Count;
        return res;
    }

    public Team()
    {
    }

    public void add(HeroStats hero)
    {
        if (team.Count <= 5)
            team.Add(hero);
        else
        Console.WriteLine("Team is full , create another team");
     }

    public List<HeroStats> print() {
        List<HeroStats> l = new List<HeroStats>();
        foreach (HeroStats h in team)
            l.Add(h);
        return l;
    }
}

In another class i want to do a foreach on an object of type Team

public void fitness(Team t)
    {

        int score;
        foreach(HeroStats hero in t)
        {
        }

    }

How can I make the foreach function work without discarding the hashset ?

Upvotes: 1

Views: 17873

Answers (2)

brz
brz

Reputation: 6016

You have to implement IEnumerable in your Team class.

public class Team : IEnumerable<HeroStats>
{
    private HashSet<HeroStats> stats = new HashSet<HeroStats>();

    public IEnumerator<HeroStats> GetEnumerator()
    {
        return stats.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return stats.GetEnumerator();
    }
}

Upvotes: 4

Servy
Servy

Reputation: 203850

You need to expose a sequence of hero, which you can get from your set, externally. You don't want full access to the entire collection, as then they could add heros when the set is full, or take out heros they shouldn't, etc. You just want them to be able to iterate through all of the heros that are there. IEnumerable<T> exposes exactly that functionality.

public IEnumerable<HeroStats> Heros { get { return team; } }

The caller can now write:

public void fitness(Team t)
{
    int score;
    foreach(HeroStats hero in t.Heros)
    {
        DoStuffWithHero(hero);
    }
}

Upvotes: 4

Related Questions