gpt4 book ai didi

c# - 词典顺序变更

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:53 25 4
gpt4 key购买 nike

我有一本字典。

  Dictionary<int, string> inboxMessages = new Dictionary<int, string>();

此字典包含具有自己唯一 ID 的消息(消息越新,ID 越高)。我将消息放在选择器 (xamarin) 中,但它首先显示最旧的消息。我该如何更改?

选择器:

 inboxPicker = new Picker
{
WidthRequest = 320,
};
foreach (string inboxMessage in inboxMessages.Values)
{
inboxPicker.Items.Add(inboxMessage);
}

我如何收到消息:

        private async Task getMessages()
{
await Task.Run(async () => {
MailModel[] mails = await api.GetMails(App.userInfo.user_id);

foreach (MailModel mail in mails)
{
inboxMessages.Add(mail.message_id,mail.sender_user_id +" "+ mail.subject +" "+ mail.time_send);
}
});
}

最佳答案

Values property字典的顺序没有排序。引用文档:

The order of the values in the Dictionary<TKey, TValue>.ValueCollection is unspecified [...]

如果您想以某种特定顺序检索值,您需要自己对其进行排序。例如:

var sorted = inboxMessages.OrderByDescending(kv => kv.Key).Select(kv => kv.Value);

foreach (string inboxMessage in sorted)
{
inboxPicker.Items.Add(inboxMessage);
}

这从字典中检索 KeyValuePairs,将它们按 int 降序排列键,然后返回值的枚举。

关于c# - 词典顺序变更,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41661524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com