>ItemName BeforeItem AfterItem >------------------------------------------ >"First" >"Second" >"Third" >"B4Second" "Second" >"BetweenSecond" "Second" "B4Second" > >>
Third First B4Second BetweenSecond SecondIf we suppose that rows with empty BeforeItem and empty AfterItem imply a natural order, then I can produce your output
static void doit() { string [,] s = // { { "First", null, null}, { "Second", null, null }, { "Third", null, null }, { "B4Second", "Second", null }, { "BetweenSecond", "Second", "B4Second" } } ; SortThem(s, true); } static void SortThem( string[,] s, bool respectInputOrder) { var v = new Graph.TopologicalSort<string>(); int i; string successor, predecessor, lastItem = null; for (i = 0; i < s.GetLength(0); i++) { // 0 and 1 predecessor = s[i, 0]; successor = s[i, 1]; if (respectInputOrder && (successor == null) && (s[i, 2] == null) ) { if (lastItem != null && !v.Edge(predecessor, lastItem)) throw new Exception("program error"); lastItem = predecessor ; } if (successor == null) { if (!v.Edge(predecessor)) throw new Exception("program error"); } else { if( !v.Edge(successor, predecessor) ) throw new Exception("program error"); } // 1 && 2 successor = predecessor ; // s[i, 0] predecessor = s[i, 2]; if (predecessor != null) { if (!v.Edge(successor, predecessor)) throw new Exception("program error"); } } // Sort them Queue<string> output; if (!v.Sort(out output)) { // cycles Console.WriteLine("a cycle has been detected"); while (output.Count > 0) Console.WriteLine(output.Dequeue()); } else { Console.WriteLine("Evaluation order is"); while (output.Count > 0) Console.WriteLine(output.Dequeue()); } }Topological sort can be downloaded here: http://www.atoutfox.com/articles.asp?ACTION=FCONSULTER&ID=0000000526