【问题标题】:Cannot get the value from list key C#无法从列表键 C# 中获取值
【发布时间】:2014-10-03 00:08:50
【问题描述】:

我尝试通过他们的键从列表中获取值。我将列表从一种形式发送到另一种形式。这是 Windows 窗体应用程序请参阅我的代码:

    /* 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"];

    }

我认为这显然是我尝试做的,所以任何帮助都很棒!

已解决:感谢 stackoverflow 用户 Sriram Sakthivel!解决方案:

    /* First form*/
    Dictionary<string, string> openWith = new Dictionary<string, string>(); 
    openWith.Add("cat", "test");
    editAccount f3 = new editAccount(connection, openWith);

    /* Form 2 */
    private Dictionary<string, string> _theList;

    public editAccount(string connection, Dictionary<string, string> arr)
    {
        InitializeComponent();
        _theList = arr;


        label1.Text = _theList["cat"];

    }

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    如果您需要通过key 访问值,那么您应该使用键控集合,例如Dictionary。列表只能通过索引访问,它没有定义以字符串为参数的索引器。

    除此之外,键默认区分大小写。如果您需要不敏感的密钥,您可以use this

    【讨论】:

    • Dictionary 与 List 有什么不同呢?所以我应该替换它们?
    • @TorrBallen Dictionary 基于HashTable,它通过键提供对元素的有效访问。如果您需要通过密钥访问,那么Dictionary 是您的最佳选择。
    • 再次感谢,Dictionary 工作得很好。用最终代码更新了主帖。
    【解决方案2】:

    如果您想通过按键查找内容,您不需要 List&lt;KeyValuePair&lt;string, int&gt;&gt;你想要一个 Dictionary&lt;string, int&gt;。因此,替换所有出现的 List&lt;KeyValuePair&lt;string, int&gt;&gt;,并且如前所述,您的密钥区分大小写。

    对于列表,[n] 索引器需要一个 int 并用于获取列表中的第 n 个项目

    【讨论】:

      【解决方案3】:

      您应该为此使用字典,它通过对键进行散列进行优化,以便更快地检索。

      也就是说,如果您想要一个列表,一种选择是对其执行 linq 查询。

      _list.Where(p => p.Key == "cat");
      

      【讨论】:

        【解决方案4】:

        如果您不关心大小写,您可以在设置或使用密钥时使用String.ToLowerString.ToUpper 方法。

        如果你想通过string index访问你的值,你应该使用Dictionary&lt;String, Int32&gt;

        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();
        }
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-23
        • 2020-06-01
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多