当我单击按钮时,我想按键对字典进行排序。它应该是这样的: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;
}
}
}
}
答案 0 :(得分:1)
您可能想使用SortedList类而不是字典。该词典是一个哈希表,与您打算使用的用法不同。
答案 1 :(得分:0)
如果您只想按键顺序打印出无序词典的内容,请使用OrderBy
public void PrintSortedDictionary(Dictionary<int, string> dictionary)
{
dictionary.OrderBy(kvp => kvp.Key).ToList().ForEach(kvp => Console.WriteLine($"Key: {kvp.Key} - Value: {kvp.Value}"));
}