【发布时间】:2018-12-20 15:59:52
【问题描述】:
当我点击按钮时,我想按键排序这个字典。它应该是这样的:https://gyazo.com/2f03244e94627153e8f7cb3fef4862d5
试图用冒泡排序以某种方式做到这一点,但无法弄清楚。
public partial class MainWindow : Window
{
Dictionary<int, string> dict = new Dictionary<int, string>();
public MainWindow()
{
InitializeComponent();
}
private void btn_add_Click(object sender, RoutedEventArgs e)
{
//Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Clear();
//int asd = Convert.ToInt32(txt1.Text);
string asd = Convert.ToString(txt2.Text);
dict.Add(Convert.ToInt32(txt1.Text), asd);
string lol = "";
foreach (var pair in dict)
{
lol += pair.Key + "-" + pair.Value;
}
list.Items.Add(lol);
}
private void btn_sort_Click(object sender, RoutedEventArgs e)
{
int asd = dict.ElementAt(1).Key;
for (int i = 1; i < dict.Count; i++)
{
for (int j = i + 1; j < dict.Count; j++)
{
if (dict.ElementAt(i).Key > dict.ElementAt(j).Key)
{
asd = dict.ElementAt(i).Key;
dict.ElementAt(i).Key = dict.ElementAt(j).Key;
dict.ElementAt(j).Key = asd;
}
}
}
}
【问题讨论】:
-
字典是无序的。
-
你尝试过 SortedDictionary 吗?
-
可以使用dict.OrderBy((kvp) => kvp.Key);进行排序
-
@jdweng 不知道该怎么做。尝试过这样的事情但不起作用gyazo.com/0ae0f663ef23f99125ff76c91d16269b
-
它必须有效。它像排序一样缠绕,但不是您期望的顺序。哪些值没有排序?
标签: c# wpf sorting dictionary