C # get the value of a subset from a dictionary by keywords

So, you can get a single dictionary[key] value or all dictionary.Values values.

What I'm looking for is a way to get all the values ​​for a given set of keys as follows:

 List<string> keys; Dictionary<string, object> dictionary; List<object> valuesForKeys = GetValuesFromDictionaryUsingKeys(dictionary, keys); 

from

 private List<object> GetValuesFromDictionaryUsingKeys(Dictionary<string, object> dictionary, List<string> keys) { //your code here } 

Of course, I could manually iterate over the list of keys and use dictionary[key] every time and again to add all the values ​​to the list, but I would like to use a more elegant way (for example, Linq).

Thanks.

+6
source share
5 answers

Try keys.Where(k => dictionary.ContainsKey(k)).Select(k => dictionary[k]) .

+10
source

Why write a function if you have a universal extension method for everyday use?

 public static IEnumerable<V> GetValues<K, V>(this IDictionary<K, V> dict, IEnumerable<K> keys) { return keys.Select((x) => dict[x]); } 

EDIT: How can you write:

 var valuesForKeys = dictionary.GetValues(keys).ToList(); 
+6
source
 private List<object> GetValuesFromDictionaryUsingKeys(Dictionary<string, object> dictionary, List<string> keys) { List<object> nList = new List<object>(); foreach (string sKey in keys) if (dictionary.ContainsKey(sKey)) nList.Add(dictionary[sKey]); return nList; } 
+2
source

Try:

  List<object> valuesForKeys = keys.Intersect( dictionary.Keys ) .Select( k => dictionary[k] ) .ToList(); 

or by request:

 private List<object> GetValuesFromDictionaryUsingKeys( Dictionary<string, object> dictionary, List<string> keys ) { // My code here return keys.Intersect( dictionary.Keys ) .Select( k => dictionary[k] ) .ToList(); } 

Use .Intersect to remove keys that are not in the dictionary faster than .Where(k => dictionary.ContainsKey(k)) .

Remove the .Intersect statement to allow an exception to be thrown for a key not found in the dictionary.

+2
source

Rawling's answer works flawlessly, but if you know in advance that the keys exist in the dictionary, it can be more clear and efficient: keys.Select(k => dictionary[k])

0
source

Source: https://habr.com/ru/post/909442/


All Articles