C# Corner
Tech
News
Videos
Forums
Trainings
Books
Events
More
Interviews
Jobs
Live
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
.NET
ADO.NET
Android
ASP.NET
C#
Databases & DBA
Design Patterns & Practices
Java
Learn iOS Programming
OOP/OOD
SharePoint
Software Testing
Web Development
WPF
View All
1
Reply
Difference Between HashSet and List<T>?
Priya Chavadiya
1y
1.2k
1
Reply
Delete Row
Delete Column
Insert Link
×
Insert
Cancel
Embed YouTube Video
×
Width (%)
Height (%)
Insert
Cancel
Table Options
×
Rows
Columns
First row as header
Create Table
Insert Image
×
Selected file:
Alignment
Left
Center
Right
Select an image from your device to upload
Upload to Server
Cancel
Submit
List: A list is a data structure that stores items in a specific order. It allows for the storage of multiple instances of the same element. The ability to access items through indexing makes it a flexible option for data management. Maintaining the order of data is crucial, and the versatility of lists is enhanced by their ability to contain multiple instances of the same item.HashSet: Unlike a list, a HashSet cannot contain duplicate elements. It operates with hash tables that provide fast operations for adding, removing, and searching elements. The HashSet class shares many similarities with the List class, such as the Add, Remove, and Contains methods. However, it lacks important features like the IndexOf method and the Count property. Ensuring the uniqueness of each element and the need for fast element verification are essential. Additionally, it is crucial to perform operations such as union and intersection on sets.Here are some real-world examples of using List and HashSet in C#:List Example: Imagine you are creating a shopping cart for your online store. You would use a list to store the items in your cart because the order of the items is important (items are added to the cart in the order they are selected). Duplicate items are allowed (users can add multiple quantities of the same item).Here is a simple example in C#: List
shoppingCart = new List
(); shoppingCart.Add("Mango"); shoppingCart.Add("Apple"); shoppingCart.Add("Mango");// Prints: Mango, Apple, Mango Console.WriteLine(string.Join(", ", shoppingCart));HashSet Example: Imagine you are building a patient management system in a hospital. Each patient ID must be unique, so you would use a HashSet to store patient IDs. The order of the patient IDs does not matter. It is often necessary to quickly check if a patient identifier is in the set.Here is a simple example in C#: HashSet
patientIds = new HashSet
(); patientIds.Add(1001); patientIds.Add(1002); patientIds.Add(1001);// Print: 1001, 1002 Console.WriteLine(string.Join(", ", patientIds));
Chulbul Singh
1y
1
Message