2

I have a class as follows:

public class User
{
    public int ID { get; set; }
    public int PPN { get; set; }

    public User(int id, int ppn)
    {
        ID = id;
        PPN = ppn;
    }
}

Of which I've declared a HashSet of it's type.

HashSet<User> users = new HashSet<User>();

Now, I want to remove the 5th entry in the following method:

    public void Delete() {
      users.Remove(5);
}

But I get the following error:

cannot convert from 'int' to 'User' 

Anybody know what the issue is and how I can resolve this?

MattTheHack
  • 1,354
  • 7
  • 28
  • 48

2 Answers2

3

A HashSet is not a list or array, it has no indexer and you cannot access an item via index. The reason is that the order is not guaranteed (if you never remove any items, it will preserve insertion order in the current implementation). If that doesn't matter you can use ElementAtOrDefault:

User fifth = users.ElementAtOrDefault(4);
if (fifth != null) users.Remove(fifth);
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Anybody know what the issue is?

The documentation for the Hashset clearly says that the remove method removes the specified element from a HashSet object. And the parameter of type T is the element to remove, and not the index OR key or anything like that.

http://msdn.microsoft.com/en-us/library/bb342694%28v=vs.110%29.aspx

how I can resolve this?

@Jonesy answered it in your comments. Use a different collection type (e.g. Generic List), because a hashset will not guarantee order, and if you want to remove a specific element and not any element at fifth position, you will not be able to do it with a hashset.

If you don't care what element is on fifth position, and you just want to remove it then the solution from @Tim Schmelter will work.

Faris Zacina
  • 14,056
  • 7
  • 62
  • 75