使用字典从选择器获取int值

时间:2016-12-18 21:41:50

标签: c# dictionary xamarin

有人告诉我,字典的键应该是唯一的,所以我改变了字典:

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

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

因为在我的情况下int是唯一的,而字符串本身并不是

但首先我可以从选择器中得到int,但现在我无法弄明白。

选择器:

    pickerRecipients = new Picker
        {
        };
        foreach (string recipientName in recipients.Values)
        {
            pickerRecipients.Items.Add(recipientName);
        }

首先我会做

    string currentlySelected = pickerRecipients.Items[pickerRecipients.SelectedIndex];

但现在它显然无法工作,但我无法找到获取int的方法(选择器显示字符串,这是一个名称,连接到它的int是唯一的用户号)

2 个答案:

答案 0 :(得分:1)

// get the key of the first match
var key = recipients.FirstOrDefault(x => x.Value == selectedName).Key;

答案 1 :(得分:0)

我没有足够的代表将其作为评论,但您的代码会有问题。例如,如果你在字典中有这个值:&#39; 1 someValue&#39;,&#39; 2 otherValue&#39;,&#39; 3 someValue&#39;并且用户将选择“someValue&#39;”。您的代码将返回1。 我想你可以尝试插入(我之前输入了一个空格(所以我可以用&#39;&#39;分开)

foreach (var recipient in recipients)
{
     pickerRecipients.Items.Add(recipient.Value + " (" + recipient.Key + ")");
}

然后使用

获取用户选择的值
string currentlySelected = pickerRecipients.Items[pickerRecipients.SelectedIndex];

将结果分开,如

var selectedIndex = currentlySelected.Split(' ').Last().Split('(', ')')[1];

您将获得所选索引。 同样,这不是您问题的直接解决方案,但如果您不考虑这个问题,您的问题会产生其他问题。