好的...这是一个垒球问题...
我只需要能够将键/值对插入特定位置的对象。我目前正在使用 Hashtable,当然,它不允许使用此功能。什么是最好的方法?
更新:另外,我确实需要通过键查找的能力。
例如...过度简化和伪代码但应该传达重点
// existing Hashtable
myHashtable.Add("somekey1", "somevalue1");
myHashtable.Add("somekey2", "somevalue2");
myHashtable.Add("somekey3", "somevalue3");
// Some other object that will allow me to insert a new key/value pair.
// Assume that this object has been populated with the above key/value pairs.
oSomeObject.Insert("newfirstkey","newfirstvalue");
提前致谢。
最佳答案
List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Key1", "Value1"),
new KeyValuePair<string, string>("Key2", "Value2"),
new KeyValuePair<string, string>("Key3", "Value3"),
};
kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));
使用这段代码:
foreach (KeyValuePair<string, string> kvp in kvpList)
{
Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}
预期的输出应该是:
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
这同样适用于 KeyValuePair 或您想要使用的任何其他类型..
编辑 -
要通过键查找,您可以执行以下操作:
var result = stringList.Where(s => s == "Lookup");
您可以通过执行以下操作对 KeyValuePair 执行此操作:
var result = kvpList.Where (kvp => kvp.Value == "Lookup");
关于c# - 如何将项目插入键/值对对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2745342/