C hashset LEARNOVITA

HashSet Collection in C# Tutorial | Complete Guide Tutorial For Free

Last updated on 16th Aug 2022, Blog, Tutorials

About author

Karan Baski (C# .Net Developer )

Karan Baski is a C# .Net Developer expert and subject specialist who has experience with Git, WPF,VB,.NET Framework,.NET Core, SVN,HTTP,.NET technology stack, WPF, C#, SQL server, Web API, ASP.NET..His articles help the learners to get insights about the Domain.

(5.0) | 19587 Ratings 2113

Introduction :

In C#HashSet is an unordered assortment of distinctive parts. This assortment is introduced in .NET 3.5. This assortment is of the generic sort assortment and it’s outlined below System.Collections.Generic namespace. it’s usually used after we wish to forestall duplicate parts from being placed within the assortment.

About C# HashSet :

last adjusted Dec three, 2021 C# HashSet educational exercise tells the simplest thanks to work with a HashSet assortment in C#.

HashSet:

HashSet addresses a bunch of qualities. It contains no copy parts. The assortment models the numerical set deliberation. HashSet doesn’t provide requests for parts. On the off chance that we would like to stay in management, we will utilize the Sorted Set assortment.

C# HashSet count components:

The Count property returns the quantity of elements within the HashSet.

  • Program. cs
  • var brands = new HashSet();
  • brands.Add(“Wilson”);
  • brands.Add(“Nike”);
  • brands.Add(“Volvo”);
  • brands.Add(“IBM”);
  • brands.Add(“IBM”);
  • int nOfElements = brands.Count;
  • Console.WriteLine($”The set contains components”);
  • Console.WriteLine(string.Join(“, “, brands));
  • HashSet assortment in C#:

    HashSet

    An unordered assortment of fascinating things is understood as a HashSet. it’s found in System.Collections.Generic namespace. a little of the highlights of HashSet assortment square measure as per the following:

    • The HashSet assortment provides tasks with superior execution.
    • There are not any copy elements within the HashSet assortment.
    • There is no extreme limit with regards to the elements within the HashSet. The limit increments because the amount of the quantity of elements increments.
    • There is no specific request for the elements within the HashSet assortment.

    What is the use of HashSet in C#?

    In C#HashSet is an Associate in Nursing unordered assortment of fascinating elements. This assortment is conferred in. NET 3.5. It upholds the execution of sets and uses the hash table for capability.

    What is a HashSet?

    A HashSet – self-addressed by the HashSet category about the System.Collections.Generic namespace – could be a superior presentation, unordered assortment of novel elements. afterwards, a HashSet isn’t organized and doesn’t contain any copy elements. A HashSet likewise doesn’t uphold files – you’ll utilize enumerators because it were. A HashSet is often used for elite execution activities as well as a bunch of outstanding info.

    What is the HashSet assortment?

    Java HashSet category is used to create Associate in Nursing assortment that utilizes a hash table for capability. It acquires the AbstractSet category and carries out Set affiliation purposes. HashSet stores the elements by utilizing the Associate in Nursing instrument referred to as hashing. HashSet contains exceptional elements because it were. HashSet permits invalid values.

    Constructors in HashSet Collection:

      ConstructorsDescription
      HashSet () This creator initializes a brand new instance of HashSet category. This instance is empty
      HashSet(IEnumerable) This creator initializes a brand new instance of HashSet category. It contains parts traced from the required assortment with a capability to accommodate all parts traced.
      IEqualityComparer) HashSet category. It uses the required equality comparer that contains parts from the required assortment.
      HashSet(IEqualityComparer) This creator initializes a brand new instance of HashSet category. This instance is empty
      HashSet(IEnumerable, HashSet(Int32) This creator initializes a brand new instance of HashSet category. This instance is empty however it’s a reserved house for capability things.
      HashSet(Int32, IEqualityComparer) This creator initializes a brand new instance of HashSet category. It will accommodate the capability parts and use the required quality comparison.
      HashSet(SerializationInfo, StreamingContext) This creator initializes a brand new instance of HashSet category exploitation serialized information.

    Methods in HashSet Collection:

    The different ways and their description is given as follows:

      MethodsDescription
      Add(T) This property gets the IEqualityComparer object. This object is employed to see equality for the values within the set.
      Clear() This property gets the quantity of parts that area units contained in a very set.
      Clear() This technique removes all the weather from a HashSet object.
      Contains(T) This technique determines whether or not a HashSet object contains the desired component.
      CopyTo(T[]) This technique copies the weather of a HashSet object to the Associate in Nursing array.
      CreateSetComparer() This technique returns Associate in Nursing IEqualityComparer object. This object is often used for the equality testing of a HashSet object.
      Equals(Object) This technique determines if the desired object is adequate to the present object or not.
      GetEnumerator() This technique returns Associate in Nursing census taker that iterates through a HashSet object.
      GetHashCode() This technique is that the default hash performs.
      GetType() This technique gets the sort of the present instance.
      IntersectWith(IEnumerable) This technique modifies the {present|this} HashSet object to contain solely those parts that area units present therein object and within the nominal assortment.
      MemberwiseClone() This technique creates a shallow copy of the present Object.
      Remove(T) This technique removes the desired component from the HashSet object.
      RemoveWhere(Predicate) This technique removes all the weather that matches the conditions of that area unit outlined by a nominal predicate from a HashSet assortment.
      SetEquals(IEnumerable) This technique determines if a HashSet object and also the nominal assortment contain identical parts.
      SymmetricExceptWith(IEnumerable) This technique modifies the {present|this} HashSet object to contain solely those parts that area units present either therein object or within the nominal assortment, however not in each.
      ToString() This technique returns a string that represents the present object.
      TrimExcess() This technique sets the capability of a HashSet object to the particular range of parts that it contains, rounded up to a close-by, implementation-specific value.
      TryGetValue(T, T) This technique searches the set for a given worth and returns the equal worth if it finds it.

    Search a thing in a HashSet in C#:

    To look through a thing in a HashSet you can involve the Contains technique as displayed in the code piece given beneath:

    • static void Main(string[] args)
    • {
    • HashSet hashSet = new HashSet();
    • hashSet.Add(“A”);
    • hashSet.Add(“B”);
    • hashSet.Add(“C”);
    • hashSet.Add(“D”);
    • if (hashSet.Contains(“D”))
    • Console.WriteLine(“The required component is available.”);
    • else
    • Console.WriteLine(“The required component isn’t available.”);
    • Console.ReadKey();
    • }

    HashSet components are exceptional all of the time:

    Assuming that you endeavor to embed a copy component in a HashSet it would essentially be disregarded yet no runtime exemption will be tossed. The accompanying code scrap shows this.

    • static void Main(string[] args)
    • {
    • HashSet hashSet = new HashSet();
    • hashSet.Add(“A”);
    • hashSet.Add(“B”);
    • hashSet.Add(“C”);
    • hashSet.Add(“D”);
    • hashSet.Add(“D”);
    • Console.WriteLine(“The number of components is: {0}”, hashSet.Count);
    • Console.ReadKey();
    • }

    At the point when you execute the program, the result will be as displayed. Presently consider the accompanying code scrap that outlines how to copy components are disposed of:

    • string[] urban communities = new string[] {
    • “Delhi”,
    • “Kolkata”,
    • “New York”,
    • “London”,
    • “Tokyo”,
    • “Washington”,
    • “Tokyo”
    • };
    • HashSet hashSet = new HashSet(cities);
    • foreach (var city in hashSet)
    • {
    • Console.WriteLine(city);
    • }

    Whenever you execute the higher than program, the copy town names would be taken out.

    Eliminate parts from a HashSet in C#:

    To eliminate a factor from a HashSet you must decide the take away strategy. The language structure of the take away technique is given below.On the off likelihood that the factor is found within the assortment, the take away technique eliminates an element from the HashSet and returns valid on progress, counterfeit in any case.

    Promotion:

    The code bit given below shows however you’ll utilize the take away technique to eliminate a factor from a HashSet.

    • string factor = “D”;
    • if(HashSet.Contains(item))

    Promotion:

    • HashSet setA = new HashSet() ;
    • HashSet setB = new HashSet() ;
    • HashSet setC = new HashSet() ;
    • in the event that (setA.IsProperSubsetOf(setC))
    • Console.WriteLine(“setC contains all parts of setA.”);
    • if (!setA.IsProperSubsetOf(setB))
    • Console.WriteLine(“setB doesn’t contains all parts of setA.”);

    Importance of Hashset assortment in C#:

    The HashSet category carries out the ICollection, IEnumerable, IReadOnlyCollection, ISet, IEnumerable, IDeserializationCallback, and ISerializable affiliation points.

    In HashSet, the request for the element isn’t characterized. You can’t sort the parts of HashSet.

    In HashSet, the parts ought to be one in every form.

    In HashSet, copy parts aren’t permissible.

    It provides various numerical set activities, like crossing purpose, association, and distinction.

    The limit of a HashSet is the amount of parts it will hold.

    A HashSet could be a distinctive assortment implies the scale of the HashSet is of course swollen once the new parts are other.

    In HashSet, you’ll store similar kinds of parts.

    What are the distinctions between a HashSet and TreeSet assortment in Java?

    HASH SET

    HashSet doesn’t keep everything in restraint.

    HashSet utilizes approaches().

    HashSet is invalid.

    TREE SET

    TreeSet is a lightweight comparator.

    TreeSet is slower than hashset [time complexity of O(log (n))].

    TreeSet utilizes compareTo().

    TreeSet doesn’t allow invalid.

    Features for HashSet:

    • HashSet versus List – Add() technique
    • HashSet versus List – Contains() technique
    • HashSet versus List – Remove() strategy

    The phase of HashSet C#:

    Hash function
  • Taking out the Duplicate info section in HashSet
  • Alter HashSet utilizing UnionWith() technique
  • Alter Hashset utilizing ExceptWith() technique
  • Alter Hashset utilizing SymmetricExceptWith() strategy
  • Scopes of HashSet C#:

    Here area unit many putting highlights of HashSet.

    This category addresses a bunch of qualities.

    This category provides an associate degree elite execution set of activities.

    This is a bunch of assortment that contains no copy elements and there’s no explicit request for the elements placed away in it.

    In the .NET Framework four.6 delivery, the HashSet executes the IReadOnlyCollection interface aboard the ISet interface.

    The HashSet category doesn’t have any extreme limit with regards to the quantity of elements placed away in it. This limit continues to increase because the range of elements is enclosed.

    Advantage:

    • HashSet stores the elements by utilizing a system referred to as hashing.
    • HashSet contains novel elements because it were.
    • HashSet permits invalid price.
    • Simple to began
    • Less Hardware demand
    • Cross-Platform

    Disadvantage :

    • The HashSet category is non synchronized.
    • HashSet doesn’t keep the inclusion management. Here, elements are embedded supporting their hashcode.
    • not flexible
    • Absence of quantifiability
    • Incapable to repeat and Paste

    Conclusion:

    HashSet in C# .NET could be a superior exhibition assortment store. The good thing about utilizing the HashSet object is to perform normal tasks like Union, Intersection, and then forth which supplies an easy and viable secret writing expertise. Then again, List object has the part of issue requesting, duplication, and then forth.

    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses