简体   繁体   English

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

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

Given a list: 给定一个列表:

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

(NOTE: there are multiple values for the key "qwer" and multiple keys for the value "asdf".) (注意:键“ qwer”有多个值,值“ asdf”有多个键。)

1) Is there a better way to return a list of all keys than just doing a foreach on the KeyValuePair List? 1)是否有比仅在KeyValuePair列表上执行foreach更好的方法来返回所有键的列表?

2) Similarly, is there a better way to return a list of all values for a given key than using a foreach? 2)同样,是否有比使用foreach更好的方法来返回给定键的所有值的列表?

3) And then, how about returning a list of keys for a given value? 3)然后,如何返回给定值的键列表?

Thanks... 谢谢...

// #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" }

It sounds like you would benefit from using something like: 听起来您会从使用以下内容中受益:

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
}

It would be relatively easy to create a basic mutli-value dictionary class using a Dictionary and List. 使用Dictionary and List创建基本的多值字典类相对容易。

This blog post talks more about Microsoft's MultiDictionary type available via NuGet. 这篇博客文章讨论了更多有关可以通过NuGet获得的Microsoft MultiDictionary类型的信息。

You can use NameValueCollection from System.Collection.Specialized namespace: 您可以从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");

Example of use: 使用示例:

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 https://msdn.microsoft.com/zh-cn/library/system.collections.specialized.namevaluecollection%28v=vs.110%29.aspx

Well you could definitly use your LINQ. 好吧,您可以明确使用LINQ。 But it's not "better" (in term of performance) since looping is already fast. 但这并不是“更好”(就性能而言),因为循环已经非常快。 It is perhaps more readable (personnal preference). 它可能更具可读性(个人喜好)。 For all the answers below, be aware that you need to have the System.Linq namespace imported. 对于以下所有答案,请注意,您需要导入System.Linq命名空间。 They also return IEnumerable<T> that are lazy loaded (executed when iterated over). 它们还返回IEnumerable<T> ,它们是延迟加载的(迭代时执行)。 If you want to return a concrete list, you can call the .ToList() extension . 如果要返回具体列表,则可以调用.ToList()扩展名

Is there a better way to return a list of all keys than just doing a foreach on the KeyValuePair List? 是否有比仅在KeyValuePair列表上进行foreach更好的方法来返回所有键的列表?

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? 同样,是否有比使用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();

For more information on LINQ, look at LINQ (Language-Integrated Query) 有关LINQ的更多信息,请查看LINQ(语言集成查询)

I would use ILookup<K,V> in your case. 我将在您的情况下使用ILookup<K,V> It is like a dictionary but you can get the values as IEnumerable<V> with the same key. 它就像一个字典,但是您可以使用相同的键将值作为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);
}

or simply 或简单地

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

Are you reading this and wondering why someone made some code have an IEnumerable<KeyValuePair<A,B>> instead of a Dictionary<A,B> but don't feel like asking and just want to get done? 您是否正在阅读此书,并且想知道为什么有人使某些代码具有IEnumerable <KeyValuePair <A,B >>而不是Dictionary <A,B>,但又不想问而只想完成?

if (collection == null)
    return null;

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

1: 1:

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

2: 2:

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

3: 3:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 排序列表 <KeyValuePair<string, double> &gt;在c#中 - Sort List<KeyValuePair<string, double>> in c# c#排序列表 <KeyValuePair<int, string> &gt; - c# Sorting a List<KeyValuePair<int, string>> 将定界字符串转换为KeyValuePair列表 <string,string> 在C#中 - Convert a delimited string to a List of KeyValuePair<string,string> in C# 如何 select 列表中的键值对列表<list<keyvaluepair<string,double> >> 并修改它们的值? C# </list<keyvaluepair<string,double> - How to select list of keyvaluepairs in List<List<keyvaluepair<string,double>>> and modify their values ? C# 如何将listBox选中的项目作为KeyValuePair <string, string> 在C#? - How to get listBox selected item as KeyValuePair<string, string> in C#? 列表中的分区键<keyvaluepair> c#</keyvaluepair> - Partition Keys in List<KeyValuePair> c# 映射列表<KeyValuePair<string,int> &gt; 在 C# 中自定义对象 - Mapping List<KeyValuePair<string,int>> to custom object in C# 使用哪个 c# 集合而不是 List <KeyValuePair<string, double> &gt;? - which c# collection to use instead of List<KeyValuePair<string, double>>? 从列表返回匹配项 <KeyValuePair<string,string> &gt; - Returning a match from a List<KeyValuePair<string,string>> 如何使用 KeyValuePair 从 List 中获取 ListDictionary 来翻译一些字符串? - How to get ListDictionary from List with KeyValuePair to translate some string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM