I'm currently having trouble finding a way to get an IOrderedEnumerable from a SortedList.
I have a complex type, we'll just call it 'A' for now, that can be decomposed into an enumerable of type 'A'. I'm currently creating a SortedList in a recursive decomposition function where the key, an int
, is related to the order the piece was decomposed in:
private static SortedList<int, A> RecursivelyBuildMySortedList(A myValue)
{
if (myValue == StopCondition())
{
return new SortedList<int, A> { { 1, myValue } };
}
var left = RecursivelyBuildMySortedList(myValue.Left);
var right = RecursivelyBuildMySortedList(myValue.Right).Select(entry => new KeyValuePair<int, A>(entry.Key + left.Count, entry.Value)).ToList();
right.ForEach(pair => left.Add(pair.Key, pair.Value));
return left;
}
However, I don't want to expose the SortedList to consumers since the value of the key, related to decomposition order, has little meaning to consumers (especially as an int
). The only thing a consumer needs to care about is what the final ordering of the pieces was so that each piece can be processed in the correct order. I would prefer to expose an IOrderedEnumerable to consumers. I thought this would be a fairly simple task since a SortedList is in many ways very similar to an OrderedEnumerable, but I've not been able to find a good conversion yet:
public static IOrderedEnumerable<A> Decompose(A myValue)
{
SortedList<int, A> mySortedList = RecursivelyBuildMySortedList(myValue);
// Can't find a way to preserve the order of the objects during 'OrderBy'
// mySortedList.Select(keyValuePair => keyValuePair.Value).OrderBy(obj => obj.index);
// The select statement would not match the return type that promises IOrderedEnumerable
// mySortedList.OrderBy(keyValuePair => keyValuePair.Key).Select(keyValuePair => keyValuePair.Value);
}
Does anyone have a method for extracting an IOrderedEnumerable from a SortedList for consumption? As a side note, I'm aware that:
return mySortedList.Select(keyValuePair => keyValuePair.Value);
Would return an IEnumerable that would preserve order 'under the hood', but due to how important the order in which the enumerable is processed is, I would rather the return type be descriptive enough to convey that the underlying collection is ordered (to make the API more readable).