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

Advertisements

Using immutable collections for thread-safe read-only operations in .NET

Sometimes you have a scenario where multiple threads need to read from the same shared collection. We’ve looked at the 4 concurrent, i.e. thread-safe collection types on this blog that are available in the System.Collections.Concurrent namespace. They can be safely used for both concurrent writes and reads.

However, if your threads strictly only need to read from a collection then there’s another option. There are collections in the System.Collections.Immutable namespace that are immutable, i.e. read-only and have been optimisied for concurrent read operations.

Read more of this post

A common platform for concurrent bags, stacks and queues in .NET

We’ve looked at the available concurrent collections in .NET before:

3 of these objects implement the same interface. Can you guess which three are similar in some sense? Stacks, bags and queues differ from dictionaries in that elements in those collections cannot be retrieved by an index of any sort. You can take/pop/dequeue the elements one by one but you cannot get to element #3 without first removing all elements before that.

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.

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

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

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

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

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: