C#从List <KeyValuePair <string,string>中获取键和值

fro*_*_jr 13 c# list keyvaluepair

给出一个清单:

    private List<KeyValuePair<string, string>> KV_List = new List<KeyValuePair<string, string>>();
    void initList()
    {
        KV_List.Add(new KeyValuePair<string, string>("qwer", "asdf"));
        KV_List.Add(new KeyValuePair<string, string>("qwer", "ghjk"));
        KV_List.Add(new KeyValuePair<string, string>("zxcv", "asdf"));
        KV_List.Add(new KeyValuePair<string, string>("hjkl", "uiop"));
    }
Run Code Online (Sandbox Code Playgroud)

(注意:"qwer"键有多个值,值"asdf"有多个键.)

1)有没有更好的方法来返回所有键的列表,而不仅仅是在KeyValuePair列表上执行foreach?

2)同样,有没有比使用foreach更好的方法返回给定键的所有值列表?

3)然后,如何返回给定值的键列表?

谢谢...

Jas*_*zun 23

// #1: get all keys (remove Distinct() if you don't want it)
List<string> allKeys = (from kvp in KV_List select kvp.Key).Distinct().ToList();
// allKeys = { "qwer", "zxcv", "hjkl" }

// #2: get values for a key
string key = "qwer";
List<string> values = (from kvp in KV_List where kvp.Key == key select kvp.Value).ToList();
// values = { "asdf", "ghjk" }

// #3: get keys for a value
string value = "asdf";
List<string> keys = (from kvp in KV_List where kvp.Value == value select kvp.Key).ToList();
// keys = { "qwer", "zxcv" }
Run Code Online (Sandbox Code Playgroud)


Fab*_*jan 6

您可以使用 System.Collection.Specialized 命名空间中的 NameValueCollection:

NameValueCollection  KV_List = new NameValueCollection();

KV_List.Add("qwer", "asdf");
KV_List.Add("qwer", "ghjk");
KV_List.Add("zxcv", "asdf");
KV_List.Add("hjkl", "uiop");
Run Code Online (Sandbox Code Playgroud)

使用示例:

string singleValue = KV_List["zxcv"];  // returns "asdf"
string[] values = KV_List.GetValues("qwer");  // returns "asdf, "ghjk"
string[] allKeys = KV_List.AllKeys;
string[] allValues = KV_List.AllKeys;
Run Code Online (Sandbox Code Playgroud)

https://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection%28v=vs.110%29.aspx


Rob*_*ick 5

听起来你会受益于使用类似的东西:

Dictionary<string, List<string>> kvlist;

kvlist["qwer"] = new List<string>();
kvlist["qwer"].Add("value1");
kvlist["qwer"].Add("value2");

foreach(var value in kvlist["qwer"]) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

使用Dictionary和List创建基本的多值字典类会相对容易.

这篇博文更多地讲述了通过NuGet提供的Microsoft的MultiDictionary类型.