0

I have a class, let's say Player, with a name and some attributes:

public class Players
{
    public string PlayerName { get; set; }
    public IList<Goal> Goals { get; set; }
    ...
}

I want to create a custom collection class, PlayerCollection, but using a Dictionary instead of a list for quicker search. So:

public class PlayersCollection
{
    private readonly IDIctionary<string, Player> _players;
    ....

Using a dictionary with the player name as the key will make things easier in the rest of my program. Now I'd like to implement IEnumerable<Player>, in order to iterate over the player class, but I can't use the dictionary's enumerator, because it is implemented on KeyValuePair<string, Player>.

How can I do that?

Phate01
  • 2,499
  • 2
  • 30
  • 55

2 Answers2

3

Try this:

public class PlayersCollection : IEnumerable<Player>
{
    private readonly IDictionary<string, Player> _players;

    public IEnumerator<Player> GetEnumerator()
    {
        return _players.Select(player => player.Value).GetEnumerator();
    }
}

If you are looking for a collection with a quick search I suggest you to read about HashSet<T> which is part of the framework.

YuvShap
  • 3,825
  • 2
  • 10
  • 24
  • Actually you should be able to use .Values instead of selecting the values. Performance will be improved – Phate01 Nov 12 '16 at 19:38
2

The KeyedCollection class is perfect for your situation. It lets you look up by a property of members of the collection. The only thing you need to do is create a derived class that has a selector for the property.

public class PlayersCollection : KeyedCollection<string, Players>
{
    protected override string GetKeyForItem(Players item)
    {
        return item.PlayerName;
    }
}

When you get the enumerator for the PlayersCollection it will be a IEnumerable<Players>.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431