How to insert an item into a key/value pair object?

后端 未结 7 982
长情又很酷
长情又很酷 2021-01-31 13:23

Ok...here\'s a softball question...

I just need to be able to insert a key/value pair into an object at a specific position. I\'m currently working with a Hashtable whic

7条回答
  •  深忆病人
    2021-01-31 14:15

    List> kvpList = new List>()
    {
        new KeyValuePair("Key1", "Value1"),
        new KeyValuePair("Key2", "Value2"),
        new KeyValuePair("Key3", "Value3"),
    };
    
    kvpList.Insert(0, new KeyValuePair("New Key 1", "New Value 1"));
    

    Using this code:

    foreach (KeyValuePair kvp in kvpList)
    {
        Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
    }
    

    the expected output should be:

    Key: New Key 1 Value: New Value 1
    Key: Key 1 Value: Value 1
    Key: Key 2 Value: Value 2
    Key: Key 3 Value: Value 3
    

    The same will work with a KeyValuePair or whatever other type you want to use..

    Edit -

    To lookup by the key, you can do the following:

    var result = stringList.Where(s => s == "Lookup");
    

    You could do this with a KeyValuePair by doing the following:

    var result = kvpList.Where (kvp => kvp.Value == "Lookup");
    

    Last edit -

    Made the answer specific to KeyValuePair rather than string.

提交回复
热议问题