Sort Tasks by Column in Gantt Chart

Overview

When rendering Gantt charts, it’s often useful to display tasks in a specific order — by start date, priority, duration, or custom fields — rather than by their default task ID. Aspose.Tasks for .NET allows you to apply custom sorting logic before rendering using the SaveOptions.TasksComparer delegate.

This enables sorting tasks by any column defined in the Gantt chart view, ensuring the final visual output aligns with reporting or presentation needs.

Aspose.Tasks for .NET provides the ability to sort tasks by any column in the Gantt chart view. This is accomplished with the help of the comparer method SaveOptions.TasksComparer before rendering in Gantt chart. The default comparer sorts tasks by task ID if no other option is specified.

Default vs Custom Task Sorting

By default, tasks in a project are rendered in the order of their Task.Id. To override this behavior, you can assign a custom IComparer<Task> to the TasksComparer property.

Examples of fields you may want to sort by:

Example: Sort Tasks by Start Date

The following example demonstrates how to sort tasks by their Start property before rendering to an image.

 1class SortTasksByColumnInGanttChart
 2{
 3    public static void Run()
 4    {
 5        Project project = new Project("New Project.mpp");
 6        SaveOptions options = new PdfSaveOptions();
 7        options.Timescale = Timescale.Months;
 8
 9        options.TasksComparer = new TasksNameComparer();
10        project.Save("SortedByNames_out.pdf", options);
11
12        options.TasksComparer = new TasksDurationComparer();
13        project.Save("SortedByDurations_out.pdf", options);
14    }
15
16    public class TasksNameComparer : IComparer<Task>
17    {
18        public int Compare(Task x, Task y)
19        {
20            return x.Get(Tsk.Name).CompareTo(y.Get(Tsk.Name));
21        }
22    }
23
24    public class TasksDurationComparer : IComparer<Task>
25    {
26        public int Compare(Task x, Task y)
27        {
28            Duration durX = x.Get(Tsk.Duration);
29            Duration durY = y.Get(Tsk.Duration);
30            return durX.TimeSpan.CompareTo(durY.TimeSpan);
31        }
32    }
33}

Custom Comparer Implementation

Below is a simple custom comparer you can plug into SaveOptions.TasksComparer:

1class SortByStartDate : IComparer<Task>
2{
3    public int Compare(Task x, Task y)
4    {
5        return DateTime.Compare(x.Get(Tsk.Start), y.Get(Tsk.Start));
6    }
7}

Assign the comparer:

1var options = new ImageSaveOptions(SaveFileFormat.Png)
2{
3    TasksComparer = new SortByStartDate()
4};
5project.Save("sorted-output.png", options);

Summary

Using TasksComparer, you can fully control how tasks are ordered in the rendered Gantt chart, providing flexibility for reporting, printing, or visual analysis.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.