C# 如何按键对这本词典排序
当我点击按钮时,我想按键对这本词典进行排序。它应该是这样的: 我试着用气泡排序法,但没办法解决C# 如何按键对这本词典排序,c#,wpf,sorting,dictionary,C#,Wpf,Sorting,Dictionary,当我点击按钮时,我想按键对这本词典进行排序。它应该是这样的: 我试着用气泡排序法,但没办法解决 public partial class MainWindow : Window { Dictionary<int, string> dict = new Dictionary<int, string>(); public MainWindow() { InitializeComponent(); } private v
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;
}
}
}
}
如果只想按键顺序打印无序词典的内容,请使用OrderBy对词典进行排序
您可能希望使用类而不是字典。字典是一个哈希表,与您要执行的操作有不同的用法。字典是无序的。您是否尝试了SortedDictionary?您可以使用dict.OrderBykvp=>kvp.Key对其进行排序@我不知道怎么做。尝试过类似的方法,但不起作用。它必须起作用。它像是在排序,但不是按照你期望的顺序。什么值没有排序?这是wpf,所以我不想用ConsoleWriteLine打印出来字典的排序没有改变,只是按键排序。一旦字典被分类,你可以做你想做的事情,把内容放在标签、字符串或任何你需要的地方。
public void PrintSortedDictionary(Dictionary<int, string> dictionary)
{
dictionary.OrderBy(kvp => kvp.Key).ToList().ForEach(kvp => Console.WriteLine($"Key: {kvp.Key} - Value: {kvp.Value}"));
}