How to Sort Layers Alphabetically


DotSpatial is an open-source project that contains controls which can be used to manipulate and display geographic information. This article explains how to create a DotSpatial extension by using the online template. The extension we are creating will allow the user to sort the layers so that they appear in the Legend alphabetically.

Getting Started

If you are not familiar with creating a simple DotSpatial-based extension, please consider the introductory article. For practical purposes, we assume you are coming to this article after having completed the previous one. This article is based on DotSpatial 1.2.

Creating a New Project

Create a new project using the DotSpatial Plugin Template. You may delete the Readme.txt and modify the name of the MyPlugin1 class (to reflect the functionality provided by the extension). I named mine SortLayersPlugin. Change the caption of the SimpleActionItem from “My Button Caption” to “Sort Layers”.

Replace the ButtonClick event handler with the following code, which is explained inline.

public void ButtonClick(object sender, EventArgs e)
    // Get a list of layers sorted alphabetically by LegendText.
    var newLayers = App.Map.Layers.OrderByDescending(l => l.LegendText).ToList();

    // Suspending events speeds our changes up and prevents redrawing multiple times.
    // The events will be called only once, when we call ResumeEvents().

    // By default, it appears some part of the layer is disposed when it is removed from the collection.
    // If we were to use App.Map.Layers.Clear(), we would stlil need to LockDispose on each layer.
    while (App.Map.Layers.Any())
        var layer = App.Map.Layers[0];

    // As we add each layer back in, in the correct order, we UnlockDispose so that the layer can be disposed
    // at the appropriate time.
    foreach (IMapLayer newLayer in newLayers)


Build and run the application. You can add a few layers and then use the menu item to sort them.


Points of Interest

You can add another button to sort the layers in reverse alphabetical order by replacing App.Map.Layers.OrderByDescending(…)… with App.Map.Layers.OrderBy(…)….


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s