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

C# get keys and values from List<KeyValuePair<string, string>

给定一个列表:

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

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

1) 除了在 KeyValuePair 列表上执行 foreach 之外,是否有更好的方法来 return 所有键的列表?

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

3) 然后,return 为给定值创建一个键列表怎么样?

谢谢...

1:

KV_List.Select(i => i.Key).ToList()

2:

KV_List.Where(i => i.Key == filterByKey).Select(i => i.Value).ToList()

3:

 KV_List.Where(i => i.Value == filterByValue).Select(i => i.Key).ToList()
// #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" }

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

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
}

使用字典和列表创建基本的多值字典class会相对容易。

本文 blog post 详细讨论了可通过 NuGet 获得的 Microsoft MultiDictionary 类型。

您可以使用 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");

使用示例:

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;

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

好吧,您绝对可以使用 LINQ。但它不是 "better" (就性能而言),因为循环已经很快了。它可能更具可读性(个人偏好)。对于下面的所有答案,请注意您需要导入 System.Linq 命名空间。它们还 return IEnumerable<T> 是延迟加载的(迭代时执行)。如果你想return一个具体的列表,你可以调用.ToList() extension.

Is there a better way to return a list of all keys than just doing a foreach on the KeyValuePair List?

KV_List.Select(kvp => kvp.Key);

Similarly, is there a better way to return a list of all values for a given key than using a foreach?

var theKeyToLookFor = "qwer";
KV_List.Where(kvp => kvp.Key == theKeyToLookFor).Select(kvp => kvp.Value);

And then, how about returning a list of keys for a given value?

var theValueToLookFor = "asdf";
KV_List.Where(kvp => kvp.Value == theValueToLookFor)
       .Select(kvp => kvp.Value)
       .ToList();

有关 LINQ 的更多信息,请查看 LINQ (Language-Integrated Query)

我会在你的情况下使用 ILookup<K,V>。它就像一本字典,但您可以使用相同的键获取 IEnumerable<V> 的值。

ILookup<string, string> lookup = KV_List.ToLookup(x => x.Key, x => x.Value);
IEnumerable<string> list = lookup["qwer"];
foreach(string str in list)
{
    Console.WriteLine(str);
}

或者干脆

Console.WriteLine(string.Join(",", lookup["qwer"]));

您是否正在阅读本文并想知道为什么有人让一些代码具有 IEnumerable> 而不是 Dictionary 但不想问而只想完成?

if (collection == null)
    return null;

return collection 
    .Where(z => z.Key == aThing)
    .Select(z => z.Value)
    .FirstOrDefault();