C# 无法从列表键C获取值
我试图通过它们的键从列表中获取值。我把清单从一张表格发送到另一张表格。这是windows窗体应用程序请参见我的代码:C# 无法从列表键C获取值,c#,winforms,C#,Winforms,我试图通过它们的键从列表中获取值。我把清单从一张表格发送到另一张表格。这是windows窗体应用程序请参见我的代码: /* First form! */ var list1 = new List<KeyValuePair<string, int>>(); list1.Add(new KeyValuePair<string, int>("Cat", 1)); form2 f3 = new form2(connection
/* First form! */
var list1 = new List<KeyValuePair<string, int>>();
list1.Add(new KeyValuePair<string, int>("Cat", 1));
form2 f3 = new form2(connection , list1);
/* Form2 */
private IList<KeyValuePair<string, int>> _theList;
public editAccount(string connection, List<KeyValuePair<string, int>> arr)
{
InitializeComponent();
_theList = arr;
label1.Text = _theList["Cat"];
}
如果需要通过键访问值,则应使用键控集合,如。列表只能通过索引访问,它没有定义以字符串为参数的索引器
除此之外,默认情况下键区分大小写。如果您需要不敏感的密钥,您可以。如果您不关心大小写,您可以在设置或使用密钥时使用或方法 如果您希望通过以下方式访问您的值,也应使用:
如果你想按键查东西,你不需要 列出你想要的 词典所以,替换列表中的所有事件,正如前面所述,您的密钥区分大小写
对于列表,[n]索引器需要一个int,并用于获取列表中的第n项您应该为此使用字典,它通过哈希键进行优化,以便更快地检索 也就是说,如果您想要一个列表,一个选项是对其执行linq查询
_list.Where(p => p.Key == "cat");
IList没有以字符串作为参数的索引器。实际上,Microsoft建议您在处理键或比较等不区分大小写的内容时使用ToUpper,而不是ToLower。那么,字典里有什么不一样的东西要列出来吗?所以我应该替换em?@Torballen字典是基于它的,它通过键提供对元素的有效访问。如果您需要通过密钥访问,则可以使用字典。再次感谢,字典工作正常。用最终代码更新了主要帖子。
var list1 = new Dictionary<string, int>();
list1.Add(new KeyValuePair<string, int>("Cat".ToUpper(), 1));
form2 f3 = new form2(connection , list1);
/* Form2 */
private IDictionary<string, Int32> _theList;
public editAccount(string connection,IDictionary<string, Int32> arr)
{
InitializeComponent();
_theList = arr;
label1.Text = _theList["cat".ToUpper()].ToString();
}
_list.Where(p => p.Key == "cat");