← Back to C# Course | Chapter 9: Collections | Lesson 4 of 7

HashSet<T> क्या है

एक HashSet एक bag है जो कभी duplicates नहीं रखता, जैसे एक sticker collection जहां आप हर design की सिर्फ एक रखते हैं। यह यह जांचने के लिए बढ़िया है कि कोई चीज़ पहले से वहां है या नहीं।

In this page:

  1. HashSet<T>
Syntax
csharp
HashSet<type> setName = new HashSet<type>();
bool added = setName.Add(item);   // false if it already exists
setName.Contains(item);

HashSet<T>

HashSet<T> unique elements store करता है बिना किसी तय order और बिना duplicates के, तेज़ lookups के लिए एक hash table से backed। पहले से मौजूद कोई element जोड़ना चुपचाप नज़रअंदाज़ हो जाता है — उस स्थिति में Add false return करता है।

यह membership tests और data से duplicates हटाने के लिए आदर्श है।

Note: जब आपको सिर्फ "क्या यह मौजूद है?" की परवाह हो, order या duplicates की नहीं, तब List<T> के बजाय HashSet<T> का उपयोग करें।

उदाहरण: HashSet<T>

markup
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        HashSet<int> ids = new HashSet<int> { 1, 2, 3 };
        bool added = ids.Add(2);   // already exists
        ids.Add(4);

        Console.WriteLine(added);
        Console.WriteLine(ids.Contains(3));
        Console.WriteLine(ids.Count);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी HashSet<T> से insertion order बनाए रखने या duplicates की अनुमति देने की उम्मीद करना।
  2. Equals और GetHashCode को override किए बिना एक custom class उपयोग करना, जिससे बराबर objects अलग माने जाते हैं।
  3. index से items पढ़ना, जिसे HashSet<T> support नहीं करता।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.