Click here to Skip to main content
15,906,766 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Let me re ask this question

Say I have two tables in a database one being tasks and the other being Dependencies

The task table has one column (taskName) with all the tasks that needs to be run

The taskDependency table has 2 columns one being tasks (taskNames) and the other dependencies (taskDependsOn)

Now say I select the tasks from the task table into a list and the dependencies for the dependencies table into a List.(Dictionary wont work as some tasks has multiple dependencies)

How would I get the tasks into the right order?

1 solution

You can use a Dictionary, you just have to use it wisely!

Try a Dictionary<string, HashSet<string>> where the key is a task name and the value is the set of task names of those tasks upon which the key depends.

Preload the Dictionary with an empty HashSet for every possible task (table 1).
Update it from the DB (table 2)
Create the empty output List
Then the order is:
1. find the keys with empty dependency sets, there is no order in this group, append these to the output list (and remove them from the Dictionary).
keep a separate list of these.
1a. if the dictionary is empty, you're done.
1b. if no empty dependency sets are found, then you have dependency cycles! FAIL.
2. for all of the remaining sets in the Dictionary (i.e., the dictionary.Values)
3. remove from the set all of the tasks found in step 1.
4. back to step 1.
Share this answer
ErniedeBruin 11-Feb-14 18:51pm    
Thanx for that is was really helpful!!!
BillWoodruff 12-Feb-14 3:32am    
Matt T Heffron 12-Feb-14 12:29pm    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900