3

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);
4

1 回答 1

6

添加对ToListafter的调用OrderBy。现在您有了一个可以操作的列表(假设您不插入将保持有序的项目)。

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);

在旁注中,您将结果转换为Whereto的示例IOrderedEnumerable<Node>将在运行时因转换失败而失败。您正在调用的Where是一个没有实现该接口的具体类型。

于 2015-04-01T00:47:45.437 回答