Posted By

sureshdasari on 10/26/18


Tagged

csharp programming collections dotnet visualStudio tutlane


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

spencerberus


C# HashSet (HashSet) with Examples


 / Published in: C#
 

URL: https://www.tutlane.com/tutorial/csharp/csharp-hashset

In c#, Hashset is a generic type of collection and it is used to represent a set of unique values. The hashset in c# will allow to store only the strongly typed elements i.e. the values of specified data type.

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5.  
  6.  
  7. namespace Tutlane
  8.  
  9. {
  10.  
  11. class Program
  12.  
  13. {
  14.  
  15. static void Main(string[] args)
  16.  
  17. {
  18.  
  19. //Create a new hashset
  20.  
  21. HashSet<int> hset = new HashSet<int>();
  22.  
  23. // Add elements to hashset object.
  24.  
  25. hset.Add(1);
  26.  
  27. hset.Add(2);
  28.  
  29. hset.Add(2);
  30.  
  31. hset.Add(3);
  32.  
  33. hset.Add(3);
  34.  
  35. hset.Add(4);
  36.  
  37. Console.WriteLine("Number of Elemen in HashSet: {0}", hset.Count);
  38.  
  39. Console.WriteLine("*********HashSet Elements********");
  40.  
  41. // Accessing elements from hashset.
  42.  
  43. foreach (int item in hset)
  44.  
  45. {
  46.  
  47. Console.WriteLine(item);
  48.  
  49. }
  50.  
  51. // Creating and initializing hashset
  52.  
  53. HashSet<string> hset2 = new HashSet<string> { "welcome", "to", "tutlane", "tutlane" };
  54.  
  55. Console.WriteLine("Number of Elemen in HashSet: {0}", hset2.Count);
  56.  
  57. Console.WriteLine("*********HashSet2 Elements********");
  58.  
  59. // Accessing elements.
  60.  
  61. foreach (string item in hset2)
  62.  
  63. {
  64.  
  65. Console.WriteLine(item);
  66.  
  67. }
  68.  
  69. Console.WriteLine("Contains Value '2': {0}", hset.Contains(2));
  70.  
  71. Console.WriteLine("Contains Value '10': {0}", hset.Contains(10));
  72.  
  73. Console.ReadLine();
  74.  
  75. }
  76.  
  77. }
  78.  
  79. }

Report this snippet  

You need to login to post a comment.