c# get value subset from dictionary by keylist

2020-07-06 04:23发布

问题:

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

What I am looking for is a way to get all values for a given key set like so:

List<string> keys;
Dictionary<string, object> dictionary;

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

with

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

Of course I could iterate manually over the keylist and use dictionary[key] each time and add all the values back to a list again, but I would like to use some more elegant way (e.g. Linq).

Thanks.

回答1:

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



回答2:

Why write function when you can have generic 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: Than you can write:

var  valuesForKeys = dictionary.GetValues(keys).ToList();


回答3:

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


回答4:

Try:

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

or as requested:

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 not present in the dictionary, it´s faster than a .Where(k => dictionary.ContainsKey(k)).

Remove the .Intersect instruction to allow raising an exception for a key not found in the dictionary.



回答5:

Rawling answer works flawlessly, but if you know beforehand the keys exist on the dictionary, this may be more clear and efficient: keys.Select(k => dictionary[k])



标签: c# dictionary