Sorting Tasks by Name

Sorting Tasks

While working with a project using Aspose.Tasks, the tasks in the project can be sorted by any of the fields. This article shows how to implement the IComparable interface to sort tasks by name.

First, define a class that implements the IComparable interface. Then traverse the tasks in the project and sort them by name.

Implementing the IComparable Interface

 1int32_t SortTasksByName::TaskNameComparer::Compare(System::SharedPtr<Task> const &x, System::SharedPtr<Task> const &y) ASPOSE_CONST
 2{
 3    if (System::String::IsNullOrEmpty(x->Get(Tsk::Name())))
 4    {
 5        return 1;
 6    }
 7    if (System::String::IsNullOrEmpty(y->Get(Tsk::Name())))
 8    {
 9        return -1;
10    }
11    return x->Get(Tsk::Name()).CompareTo(y->Get(Tsk::Name()));
12}

Sorting Tasks by Name

 1System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
 2System::SharedPtr<Project> project = System::MakeObject<Project>(dataDir + u"project-sort.mpp");
 3System::SharedPtr<ChildTasksCollector> coll = System::MakeObject<ChildTasksCollector>();
 4TaskUtils::Apply(project->get_RootTask(), coll, 0);
 5System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Task>>> tasks = coll->get_Tasks();
 6    
 7tasks->Sort(System::MakeObject<SortTasksByName::TaskNameComparer>());
 8    
 9    
10{
11    auto task_enumerator = (tasks)->GetEnumerator();
12    decltype(task_enumerator->get_Current()) task;
13    while (task_enumerator->MoveNext() && (task = task_enumerator->get_Current(), true))
14    {
15        System::Console::WriteLine(task);
16    }
17}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.