John Ohara
John Ohara

Reputation: 2901

Return values of dictionary except for a given key

I have what seems like a very simple problem, but for some reason it's not working and I haven't been able to find a solution.

I have a dictionary, with a numeric key and a class object as the value. I want to enter a key and return all values for the dictionary except the value for the specified key.

The example below return nothing.

static readonly Dictionary<int, LinkDto> _chips = new Dictionary<int, LinkDto>()
{
    { 100, new LinkDto("url1", "text1") },
    { 200, new LinkDto("url2", "text2") },
    { 500, new LinkDto("url3", "text3") },
    { 1000, new LinkDto("url4", "text4") },
    { 1500, new LinkDto("url5", "text5") },
};

This is the method that interrogates the dictionary:

public void Build(int key)
{
    Build(_chips
        .Where(x => !_chips.ContainsKey(key))
        .Select(x => x.Value).ToList());
}

And this is the call:

    Build(1500);

I expect it to return the values for 100, 200, 500 and 1000.

Upvotes: 0

Views: 693

Answers (2)

Astrid E.
Astrid E.

Reputation: 2872

The code

_chips.Where(x => !_chips.ContainsKey(key))

will return no entries in _chips in the case where _chips does contain an entry with a key equal to key.
It will return all entries in the case where _chips contains no entry with a key equal to key.

Considering your example dictionary (containing keys 100, 200, 500, 1000, 1500) and example key value of 1500, the filtering operation actually is:

_chips.Where(x => !_chips.ContainsKey(1500))

The !_chips.ContainsKey(1500) part never changes for any of the dictionary entries (x), and will therefore have the same value when performing the filtering for all entries; regardless of the entry's Key value.

I am quite sure that you want to replace the .Where() expression with something like:

.Where(x => x.Key != key)

to filter out the entry whose Key equals the provided key value.

Upvotes: 2

Dai
Dai

Reputation: 155145


public static IEnumerable<TValue> GetOtherValues<TKey,TValue>( this IReadOnlyDictionary<TKey,TValue> dict, TKey notThisKey )
    where TKey : notnull, IEquatable<TKey>
{
    if( dict is null ) throw new ArgumentNullException(nameof(dict));

    return dict.Where( kvp => !notThisKey.Equals( kvp.Key ) ).Select( kvp => kvp.Value );
}

Upvotes: 1

Related Questions