I have a list of items that have a partial order relation, i. e, the list can be considered a partially ordered set. I want to sort this list in the same way as in this question. As correctly answered there, this is known as topological sorting.
There's a reasonably simple known algorithm to solve the problem. I want a LINQ-like implementation of it.
I already tried to use OrderBy
extension method, but I'm quite sure it's not able to make topological sorting. The problem is that the IComparer<TKey>
interface is not able to represent a partial order. This happens because the Compare
method can return basically 3 kinds of values: zero, negative, and positive, meaning are-equal, is-less-than, and is-greater-then, respectively. A working solution would only be possible if there were a way to return are-unrelated.
From my biased point of view, the answer I'm looking for might be composed by an IPartialOrderComparer<T>
interface and an extension method like this:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IPartialOrderComparer<TKey> comparer
);
How would this be implemented? How does the IPartialOrderComparer<T>
interface would look like? Would you recommend a different approach? I'm eager to see it. Maybe there's a nicer way to represent the partial order, I don't know.