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.

LIFO collections with Stack of T in .NET C#

LIFO, that is last-in-first-out, collections are represented by the generic Stack of T class in .NET. Stacks are collections where a new element is placed on top of the collection and is removed first when an item is being retrieved. Hence the item that was entered first will get to stay longest in the stack.

Let’s say that you’re throwing a party where you follow a Stack policy as far as guests are concerned. As time goes by you’d like all of them to leave eventually and the first one to go will be the last person who has arrived. This might not be a very fair way to treat your guests but there you go.

Read more of this post

Using linked lists in .NET with C#

Linked lists are very efficient if you want to insert and remove items in a collection frequently. Linked lists do not store their elements in contiguous regions in memory, like e.g. the List of T object. Instead elements in linked lists can be stored anywhere.

The elements are linked by their “next” and “previous” references. The first element will have a “next” pointer to the element that comes after that. The second element in turn will have a reference to the previous and next elements. The first element will of course only have a reference to the “next” element and “previous” will be null, whereas the last element will point to the previous element and “next” will be null. All elements in between will have two references. Such a linked list is also called a doubly linked list.

One big difference between linked lists and “normal” lists is that linked lists have no index accessors. You just cannot extract the element #3 for example without looping through the linked list and stopping at the third element.

Read more of this post

Using the KeyedCollection object in C# .NET

The abstract generic KeyedCollection object can be used to declare which field of your custom object to use as a key in a Dictionary. It provides sort of a short-cut where you’d want to organise your objects in a Dictionary by an attribute of that object.

Let’s take the following object as an example:

public class CloudServer
{
	public string CloudProvider { get; set; }
	public string ImageId { get; set; }
	public string Size { get; set; }
}

The Image IDs are always unique so the ImageId property seems to be a good candidate for a dictionary key.

Here’s an example:

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:

ObservableCollection<string> names = new ObservableCollection<string>();
names.Add("Adam");
names.Add("Eve");
names.Add("Clive");
names.Add("Anne");
names.Add("John");
names.Add("Peter");
names.Add("Hannah");

Nothing special so far I guess. This looks exactly like a “normal” collection.

The following example demonstrates the CollectionChanged event:

private static void RunObservableCollectionCode()
{
	ObservableCollection<string> names = new ObservableCollection<string>();
	names.CollectionChanged += names_CollectionChanged;
	names.Add("Adam");
	names.Add("Eve");
	names.Remove("Adam");
	names.Add("John");
	names.Add("Peter");
	names.Clear();
}

static void names_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
	Debug.WriteLine("Change type: " + e.Action);
	if (e.NewItems != null)
	{
		Debug.WriteLine("Items added: ");
		foreach (var item in e.NewItems)
		{
			Debug.WriteLine(item);
		}
	}

	if (e.OldItems != null)
	{
		Debug.WriteLine("Items removed: ");
		foreach (var item in e.OldItems)
		{
			Debug.WriteLine(item);
		}
	}
}

The NotifyCollectionChangedEventArgs object resides in the System.Collections.Specialized namespace.

If I run the RunObservableCollectionCode method I get the following output:

Change type: Add
Items added:
Adam
Change type: Add
Items added:
Eve
Change type: Remove
Items removed:
Adam
Change type: Add
Items added:
John
Change type: Add
Items added:
Peter
Change type: Reset

You can then decide how to handle additions and deletions in the event handler.

View all various C# language feature related posts here.

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

Using the HashSet of T object in C# .NET to store unique elements

The generic HashSet of T is at first sight a not very “sexy” collection. It simply stores objects with no order, index or key to look up individual elements.

Here’s a simple HashSet with integers:

HashSet<int> intHashSet = new HashSet<int>();
intHashSet.Add(1);
intHashSet.Add(3);
intHashSet.Add(5);
intHashSet.Add(2);
intHashSet.Add(10);

HashSets can be handy when you want to guarantee uniqueness. The following example will only put the unique integers in the set:

Read more of this post

Determine if two arrays are structurally equal in C# .NET

Two arrays are said to be structurally equal if they contain the same elements in the same order. Whether or not two elements are the same depends on how you define equality for your custom types. Equality for primitive types, like integers, is more or less straightforward but you’ll need to declare in code what is meant by equality for reference types.

We’ve looked at a couple of strategies to do so on this blog and here we’ll re-use the topic of implementing the IEqualityComparer of T interface.

The non-generic IStructuralEquatable interface has an equals method that accepts an object to compare with and another object which implements the non-generic IEqualityComparer interface. This is an important distinction as implementing the generic IEqualityComparer interface won’t be enough for structural equality. We’ll need to derive from the EqualityComparer base class which implements both the generic and non-generic version of IEqualityComparer. If you try to run the below example with a generic IEqualityComparer of T instance then you’ll get a compiler error.

Note that structural equality is not available for all collection types. Currently only arrays and tuples support it, i.e. they can be cast to type IStructuralEquatable. However, as List objects can be easily converted into arrays that’s not really an obstacle.

Read more of this post

Implementing equality of derived reference types by overriding the == operator with C# .NET

In this post we saw one solution to override the == operator for a reference type to implement equality checking. Here’s a reminder of the Person class:

public class Person
{
	public int Id { get; set; }
	public string Name { get; set; }
	public int Age { get; set; }

	public static bool operator ==(Person personOne, Person personTwo)
	{
		return personOne.Id == personTwo.Id;
	}

	public static bool operator !=(Person personOne, Person personTwo)
	{
		return personOne.Id != personTwo.Id;
	}

        public override int GetHashCode()
	{
		return Id;
	}
}

Read more of this post

Implementing the IEquatable of T interface for object equality in a derived class with C# .NET

In this post we saw how to implement the IEquatable of T interface for a simple Person class. We based our equality logic on the Id property of the object. We implemented the IEquatable.Equals method and also overrode the Object.Equals and GetHashCode methods.

In this post we’ll see how you might go about extending that logic in derived classes. For that purpose we’ll go with another object:

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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