.NET / C# - 将列表转换为 SortedList
将列表转换为排序列表的最佳方法是什么? 有什么好的方法可以不用循环呢? 有什么聪明的方法可以用 OrderBy() 来做到这一点吗?
总结 请阅读所有答案和评论。
What is the best way to convert a List to SortedList? Any good way to do it without cycling through it? Any clever way to do it with an OrderBy()?
WRAP UP
Please read all answers and comments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的意思是:
List
并希望将其就地排序?List
并希望创建另一个本身已排序的“列表”List
并希望创建一个SortedList
T,T>
其中键与值相同假设输入:
1 是微不足道的
2 是微不足道的
3 是微不足道的副本
并且更高效:
我不明白为什么你想做 3 但就这样吧。
Do you mean:
List<T>
and wish it to be sorted in place?List<T>
and wish to create another 'list' which is itself sortedList<T>
and wish to make aSortedList<T,T>
where the key is the same as the valueAssuming input:
1 is trivial
2 is trivial
3 is trivial with a copy
and more efficiently:
I can't see why you would want to do 3 but there you go.
现在我不知道这有多高效,但它只是一行代码:) 另外,在这个例子中我只是使用字符串本身作为选择器。 在实际场景中,您应该提前知道要使用什么作为选择器。
Now I have no clue how efficient this is, but it's one line of code :) Also, in this example I just used the string itself as the selector. In a real scenario, you should know ahead of time what you'd like to use as a selector.
了解
List
是一个智能数组,SortedList
是一个键/值二叉树。 由于它们的结构之间没有关系,因此不可能有比简单地从列表中取出每个元素并将其放入树中更有效的方法。如果您的意思是“排序列表”而不是“
SortedList
”,那么通过List.Sort()
或适当的OrderBy() 对列表进行排序就很简单了
。Understand that a
List<T>
is a smart array, and aSortedList<T, U>
is a key/value binary tree. Since there's no relationship between their structures, there can't possibly be a more effective way to do it rather than simply taking each element from the list and putting it into the tree.If you mean "sorted list" instead of "
SortedList
," then it's trivial to sort your list via eitherList.Sort()
or an appropriateOrderBy()
.我相信 LINQ 为您提供了一个 ISortedEnumerable,这可能足以满足您的目的。
The LINQ gives you an ISortedEnumerable i believe, which may be good enough for your purposes.