HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Sort List By Boolean

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortlistboolean

Problem

I have a class called Task that contain a member boolean variable Completed.

I created a list of Task objects in a variable called Tasks.

I have the following code, which sorts the objects depending on whether the Task is completed. (I want the incompleted tasks to be in the list first)

private List GetSortedTask(List tasks)
{
    List completedTaskList = new List();
    List incompleteTaskList = new List();

    for (int i = 0; i < tasks.Count; i++)
    {
        HelperObject T = task[i].getHelperObject();

        if (T != null && T.Completed)
            completedTaskList.Add(tasks[i]);
        else
            incompletetaskList.Add(tasks[i]);
    }

    //merge the two lists together
    imcompleteTaskList.AddRange(completedTaskList);

    return incompleteTaskList;
}


Is there a way to do this without creating so many lists? Thanks in advance

EDIT: Made my question a bit more specific since orderBy seems to be the correct answer, however my problem may be a bit more complicated than that.

Solution

I think my original comment in regards to using OrderBy could still possibly still even with your latest edits (and BTW that code does not compile, there is no declared task object :)).

How about something like:

var query = from task in tasks
            let helperTask = task.getHelperObject()
            select new
            {
               Completed = helperTask != null && helperTask.Completed,
               Task = task
            };

return query.OrderBy(p => p.Completed).Select(p => p.Task).ToList();


UPDATE:
Another excellent option suggested by svick to further refine and remove the anonymous object selection is something along the lines of:

var query = from task in tasks
            let helperTask = task.getHelperObject()
            orderby helperTask != null && helperTask.Completed
            select task;

return query.ToList();


I guess if I could I would do away with ToList() altogether and return IEnumerable but that depends on the context of the operation. I also personally like using an intermediate variable here (query) as I think it just helps readability. All to their own on that front though.

Code Snippets

var query = from task in tasks
            let helperTask = task.getHelperObject()
            select new
            {
               Completed = helperTask != null && helperTask.Completed,
               Task = task
            };

return query.OrderBy(p => p.Completed).Select(p => p.Task).ToList();
var query = from task in tasks
            let helperTask = task.getHelperObject()
            orderby helperTask != null && helperTask.Completed
            select task;

return query.ToList();

Context

StackExchange Code Review Q#19033, answer score: 8

Revisions (0)

No revisions yet.