.NET / C# - 将列表转换为 SortedList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/981992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET / C# - Convert List to a SortedList
提问by BuddyJoe
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()?
将 List 转换为 SortedList 的最佳方法是什么?有什么好的方法可以不用骑自行车吗?有什么聪明的方法可以用 OrderBy() 做到这一点?
WRAP UPPlease read all answers and comments.
总结请阅读所有答案和评论。
采纳答案by BFree
var list = new List<string>();
var sortedList = new SortedList<string, string>(list.ToDictionary(s => s));
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.
现在我不知道这是多么有效,但它是一行代码:) 另外,在这个例子中,我只是使用字符串本身作为选择器。在实际场景中,您应该提前知道要用作选择器的内容。
回答by ShuggyCoUk
Do you mean:
你的意思是:
- you have a
List<T>
and wish it to be sorted in place? - you have a
List<T>
and wish to create another 'list' which is itself sorted - you have a
List<T>
and wish to make aSortedList<T,T>
where the key is the same as the value
- 你有一个
List<T>
并希望它被分类到位? - 您有一个
List<T>
并希望创建另一个本身已排序的“列表” - 你有 a
List<T>
并希望SortedList<T,T>
在 key 与 value 相同的地方制作 a
Assuming input:
假设输入:
var x = new List<int>() { 3, 2, 1 };
1 is trivial
1是微不足道的
x.Sort();
2 is trivial
2 是微不足道的
// sx is an IOrderedEnumerable<T>, you can call ToList() on it if you want
var sx = x.OrderBy(i => i);
3 is trivial with a copy
3 副本微不足道
var s = new SortedList<int,int>(t.ToDictionary(i => i));
and more efficiently:
并且更高效:
var s = new SortedList<int,int>();
foreach (var i in x) { s[i] = [i]; }
I can't see whyyou would want to do 3 but there you go.
我不明白你为什么想要做 3 但你去了。
回答by mqp
Understand that a List<T>
is a smart array, and a SortedList<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.
理解aList<T>
是智能数组,aSortedList<T, U>
是键/值二叉树。由于它们的结构之间没有关系,因此不可能有比简单地从列表中取出每个元素并将其放入树中更有效的方法。
If you mean "sorted list" instead of "SortedList
," then it's trivial to sort your list via either List.Sort()
or an appropriate OrderBy()
.
如果你的意思是“排序列表”,而不是“ SortedList
”,则是微不足道通过任何排序列表List.Sort()
或适当的OrderBy()
。
回答by Will Eddins
List unsortedPersons = new List();
// ... Populate unsortedPersons ...
var sorted = from person in unsortedPersons
orderby person.Name
select person;
The LINQ gives you an ISortedEnumerable i believe, which may be good enough for your purposes.
我相信 LINQ 为您提供了一个 ISortedEnumerable,这可能足以满足您的目的。