Removing an object from IOrderedEnumerable

2.8k Views Asked by At

I sorted a dictionary like this:

var sortedListOfNodes = _nodeDictionary.Values.OrderBy((n) => n.Time);

Then I selected an element as such:

var selectedNode = sortedListOfNodes.First(n => n.Time - CurrentTime > new TimeSpan(1,0,0));

Then I did some processing on that node and at the end wanted to remove the node from the list, without destroying the sorted order.

Would the below maintain the order?

sortedListOfNodes = (IOrderedEnumerable<Node>)sortedListOfNodes.Where(node => node != selectedNode);
1

There are 1 best solutions below

0
On BEST ANSWER

Add a call to ToList after OrderBy. Now you have a list you can manipulate (assuming you don't insert items it will stay in order).

var sortedListOfNodes = _nodeDictionary.Values.OrderBy((n) => n.Time).ToList();
var selectedNode = sortedListOfNodes.First(n => n.Time - CurrentTime > new TimeSpan(1,0,0));
sortedListOfNodes.Remove(selectedNode);

On a side note your example of casting the result of Where to IOrderedEnumerable<Node> would fail at runtime with a casting failure. The Where you are calling is a concrete type that does not implement that interface.