如何将项插入键/值对对象?

Cla*_*lay 62 c# list insert

好的......这是一个垒球问题......

我只需要能够将键/值对插入到特定位置的对象中.我目前正在使用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");
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Ian*_*n P 117

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"));
Run Code Online (Sandbox Code Playgroud)

使用此代码:

foreach (KeyValuePair<string, string> kvp in kvpList)
{
    Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}
Run Code Online (Sandbox Code Playgroud)

预期产量应为:

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
Run Code Online (Sandbox Code Playgroud)

这同样适用于KeyValuePair或您想要使用的任何其他类型.

编辑 -

要按键查找,您可以执行以下操作:

var result = stringList.Where(s => s == "Lookup");
Run Code Online (Sandbox Code Playgroud)

您可以通过执行以下操作使用KeyValuePair执行此操作:

var result = kvpList.Where (kvp => kvp.Value == "Lookup");
Run Code Online (Sandbox Code Playgroud)

最后编辑 -

将答案特定于KeyValuePair而不是字符串.


Mat*_*nes 5

也许OrderedDictonary会帮助你.


Dan*_*ted 5

是否需要按键查找对象?如果没有,请考虑使用List<Tuple<string, string>>或者List<KeyValuePair<string, string>>如果您不使用 .NET 4。