views:

123

answers:

5

I find myself in a situation where I'm not sure which Collection would best suit my needs.

I have a series of task objects that will be used in the following manner...

  1. The tasks will execute repeatedly during the application's runtime.
  2. The tasks will execute in a specific order based on the priority I assign each of them. (I don't care in what order tasks with matching priorities execute.)
  3. No task will execute twice during a single iteration through the sequence, so no duplicate entries.
  4. Between iterations, tasks may be added to or removed from anywhere in the sequence based on their priority.

Were I doing this in Java, I'd be looking for a SortedSet of some kind, but Sets in C# seem to be much less straightforward. Can anyone lend some advice?

Thanks!

EDIT: Thank you to all who suggested a variety of List collections, but Lists allow duplicates. :(

+1  A: 

Why not SortedList? You'll have to supply a key however.

Vlad
A: 

Use List<> Class

            List<Task> taskList = new List<Task>();
            Task task1 = new Task();
            taskList.Add(task1);
            taskList.Remove(task1);
Asad Butt
+2  A: 

If you're using .NET 4.0 you can use a SortedSet. Even if you're not using .NET 4.0, it is worth keeping a note of this if/when you upgrade.

RichardOD
D'oh! Okay, it would seem an upgrade is in order. Thanks for the heads-up, Richard.
Syndog
Ack... .NET 4 is still in beta. Looks like I'm wrapping a List until then. Thanks for the heads-up.
Syndog
+1  A: 

You can pretty much maintain the list of tasks in any type that implements IEnumerable<T>, while List<T> is always a good choice for an internal implementation.

Assuming that tasks is an instance of IEnumerable<Task>, every time you need to execute the tasks, you can order them by the OrderBy method:

foreach(var task in tasks.OrderBy(t => t.Priority))
{
    task.Execute();
}

Alternatively, you can use the LINQ syntax:

var orderedTasks = from t in tasks
                   orderby t.Priority
                   select t;
foreach(var task in orderedTasks)
{
    task.Execute();
}
Mark Seemann
+1  A: 

Unfortunately, .NET Framework does not currently have the concept of a Set class. This class (and SortedSet for that matter) is actually to be added to the Framework in .NET 4.0.

If you can't wait for that release, or don't want to target that version of the framework, the closest thing you will get is SortedList or SortedDictionary, neither of which allow for duplicate entries, and both of which offer sorted behaviour you may find useful. In both cases, however, you will be expected to provide a key for your objects, which may not be the desired behaviour.

Programming Hero
Yeah, it's close enough for government work. Thanks, PH!
Syndog