0

I am new in MVC, so I have problem to understand what is purpose of HashSet in model. I am using ADO.net Entity Data model, system auto generate model like ..

public partial class Country
{
    public Country()
    {
        this.States = new HashSet<State>();
    }

    public int ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<State> States { get; set; }
}

any one can explain in simple language why I should use a HashSet here?

NDJ
  • 5,189
  • 1
  • 18
  • 27
Pankaj Rawat
  • 4,037
  • 6
  • 41
  • 73

2 Answers2

2

HashSet is an optimized set collection. It helps eliminates duplicate strings or elements in an array. It provides a simple syntax for taking the union of elements in a set. This is performed in its constructor.

Represents a set of values. To browse the .NET Framework source code for this type, see the Reference Source.

StackOverFlow Reference

Community
  • 1
  • 1
Amit
  • 15,217
  • 8
  • 46
  • 68
1

HashSet basically is a collection of distinct values removes the duplicates and is written within the constructor. So when the default strings are initialized to a field, it performs a check to the database whether duplicate values exists. If yes, HashSet removes them. Here is the good example of HashSet.

Suppose your table name is Student

public class Example
{

    public Example()
    {
        this.Student= new HashSet<Student>();
    }

    public int DivisionID { get; set; }
    public string DivisionName { get; set; }
}

It removes the duplicate strings within the table 'Student' with no specific order stored in it. Important note here is that it doesn't remove the duplicate from the table records, but it removes the duplicates from the table fields if any.

If you want more then you can visit this link and get your answers here: Understanding HashSet

Hope this helps.

Rohan Rao
  • 2,505
  • 3
  • 19
  • 39