Create a HashSet “Persons” in C# and add the following names to:
Karen, Sab, lea
Print the size of the HashSet “Persons” to the standard output before and after adding the names.
Print all the names in “Persons” to the standard output.
Create another HashSet “Persons2” and add the following names to it: Jodi, Alex, Gab to the Persons2
Add your name to Hashset“Persons2”
Create a new HashSet “allNames” and add both group names to it.
Print all the names in “allNames” to the standardoutput.
Remove all the names from Hashset“allNames”
Print the size of the HashSet “allNames” before and after removing all the names.
using System;
using System.Text;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
public class Person
{
string Name;
public Person(string name)
{
Name = name;
}
override public string ToString()
{
return Name;
}
}
static void Main(string[] args)
{
HashSet<Person> Persons = new HashSet<Person>();
Console.WriteLine("Size of the HashSet 'Persons' before adding = " + Persons.Count);
Persons.Add(new Person("Karen"));
Persons.Add(new Person("Sab"));
Persons.Add(new Person("Lea"));
Console.WriteLine("Size of the HashSet 'Persons' after adding = " + Persons.Count);
Console.WriteLine("List of Persons:");
foreach (Person p in Persons)
{
Console.WriteLine(p);
}
HashSet<Person> Persons2 = new HashSet<Person>();
Persons2.Add(new Person("Jodi"));
Persons2.Add(new Person("Alex"));
Persons2.Add(new Person("Gab"));
// Add my name
Persons2.Add(new Person("Bill"));
HashSet<Person> allNames = new HashSet<Person>();
allNames.UnionWith(Persons);
allNames.UnionWith(Persons2);
Console.WriteLine("List of allNames:");
foreach (Person p in allNames)
{
Console.WriteLine(p);
}
Console.WriteLine("Size of the HashSet 'allNames' before removing = " + allNames.Count);
allNames.Clear();
Console.WriteLine("Size of the HashSet 'allNames' after removing = " + allNames.Count);
}
}
}
Comments
Leave a comment