How to check whether two HashSets are equal in C# .NET

Two HashSet objects in C# are equal if they contain the same values regardless of their order in the collection.

Consider the following integer sets:

HashSet<int> intHashSetOne = new HashSet<int>()
{
	1,2,6,5,7,5
};

HashSet<int> intHashSetTwo = new HashSet<int>()
{
	2,2,8,5,9,4
};

HashSet<int> intHashSetThree = new HashSet<int>()
{
	6,7,5,5,2,1
};

Read more of this post

Getting notified when collection changes with ObservableCollection in C# .NET

Imagine that you’d like to be notified when something is changed in a collection, e.g. an item is added or removed. One possible solution is to use the built-in .NET generic collection type ObservableCollection of T which is located in the System.Collections.ObjectModel namespace. The ObservableCollection object has an event called CollectionChanged. You can hook up an event handler to be notified of the changes.

If you don’t know what events, event handlers and delegates mean then start here.

Let’s see a simple example with a collection of strings:

Read more of this post

Customise your list by overriding Collection of T with C# .NET

Imagine that you’d like to build a list type of collection where you want to restrict the insertion and/or deletion of items in some way. Let’s say we need an integer list with the following rules:

  • The allowed range of integers is between 0 and 10 inclusive
  • A user should not be able to remove an item at index 0
  • A user should not be able to remove all items at once

One possible solution is to derive from the Collection of T class. The generic Collection of T class in the System.Collections.ObjectModel namespace provides virtual methods that you can override in your custom collection.

The virtual InsertItem and SetItem methods are necessary to control the behaviour of the Collection.Add and the way items can be modified through an indexer:

Read more of this post

Implementing an enumerator for a custom object in .NET C#

You can create an enumerator for a custom type by implementing the generic IEnumerable of T interface. Normally you’d do that if you want to create a custom collection that others will be able to iterate over using foreach. However, there’s nothing stopping you from adding an enumerator to any custom type if you feel like it, it’s really simple.

Consider the following Guest class:

public class Guest
{
	public string Name { get; set; }
	public int Age { get; set; }
}

Guests can be invited to a Party:

Read more of this post

Keeping the key-values sorted by using a SortedDictionary with C# .NET

You can use the generic SortedDictionary of Key and Value to automatically keep the key value items sorted by their keys. Any time you add a new key value pair the dictionary will reorder the items. The SortedDictionary was optimised for frequent changes to its list of items. Keep in mind that the items will be sorted by their key and not their value.

Consider the following simple custom object:

public class Student
{
	public string Name { get; set; }
	public string SchoolName { get; set; }
}

Read more of this post

Return a default value from a Map in Java 8

Consider the following Employee class:

public class Employee
{
    private UUID id;
    private String name;
    private int age;

    public Employee(UUID id, String name, int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
        
    public UUID getId()
    {
        return id;
    }

    public void setId(UUID id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }    
    
    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}

Let’s put some Employee objects into a hash map:

Read more of this post

Creating sorted sets with C# .NET

The SortedSet of T object is the sorted version of the HashSet object. We’ve already seen what a HashSet can do for you in the referenced post. A SortedSet keeps the elements in increasing order.

Consider the following integer set:

SortedSet<int> sortedInts = new SortedSet<int>();
sortedInts.Add(1);
sortedInts.Add(4);
sortedInts.Add(3);
sortedInts.Add(1);
sortedInts.Add(3);
sortedInts.Add(10);
sortedInts.Add(8);
sortedInts.Add(3);
sortedInts.Add(1);
sortedInts.Add(4);
foreach (int i in sortedInts)
{
	Debug.WriteLine(i);
}

This will print…

1
3
4
8
10

Notice that duplicates were rejected to ensure uniqueness just like in the case of HashSets.

That is straightforward for primitive types like integers since .NET “knows” how to compare them. It can decide whether 10 is greater than 5, we don’t need to provide any help.

However what about reference types like your own objects, such as this one?

public class Band
{
	public string Name { get; set; }
	public int YearFormed { get; set; }
	public int NumberOfMembers { get; set; }
	public int NumberOfRecords { get; set; }
}

How can .NET decide on the ordering of your objects? We’ll need to give it a hint by providing an object which implements the generic IComparer of T interface like we saw in this post. We’ll let the Band objects be sorted by their names:

public class BandNameComparer : IComparer<Band>
{
	public int Compare(Band x, Band y)
	{
		return x.Name.CompareTo(y.Name);
	}
}

Let’s see this in action:

SortedSet<Band> bands = new SortedSet<Band>(new BandNameComparer());
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1985, Name = "Well known band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1979, Name = "Famous band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1979, Name = "Famous band", NumberOfMembers = 4, NumberOfRecords = 10 });

foreach (Band band in bands)
{
	Debug.WriteLine(band.Name);
}

This will print…

Best band
Famous band
Great band
Well known band

…so not only were the items sorted by their names but the non-unique values were rejected as well. The IComparer argument also provided a way to declare equality.

View all various C# language feature related posts here.

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Love to use Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Ricos Blog zu Softwaredesign- und architektur

Ideen und Gedanken rund um Softwaredesign und -architektur, Domain-Driven Design, C# und Windows Azure

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: