I have a dictionary of the type:
IDictionary<foo, IEnumerable<bar>> my_dictionary
bar class looks like this:
class bar { public bool IsValid {get; set;} }
How can I create another dictionary with only those items that have IsValid = true.
I tried this:
my_dictionary.ToDictionary( p=> p.Key, p=> p.Value.Where (x => x.IsValid));
The problem with above code is that this creates a key with empty enumerable, if all the elements for that key were IsValid = false.
for example:
my_dictionar[foo1] = new List<bar> { new bar {IsValid = false}, new bar {IsValid = false}, new bar {IsValid = false}}; my_dictionary[foo2] = new List<bar> {new bar {IsValid = true} , new bar{IsValid = false}; var new_dict = my_dictionary.ToDictionary( p=> p.Key, p=> p.Value.Where (x => x.IsValid)); // Expected new_dict should contain only foo2 with a list of 1 bar item. // actual is a new_dict with foo1 with 0 items, and foo2 with 1 item.
How do I get my expected.
A dictionary is a useful data structure that allows you to store key-value pairs. You can efficiently access a value from the dictionary using its key. Dictionaries in C# support actions like removing a value or iterating over the entire set of values.
So in general, you use dictionary when you need to search in some collection by some key. Save this answer. Show activity on this post. You use Dictionary<TKey,TValue> when you need to store values with some unique keys associated to them, and accessing them by that key is convenient for you.
Something like this?
my_dictionary .Where(p=> p.Value.Any(x => x.IsValid)) .ToDictionary( p=> p.Key, p=> p.Value.Where (x => x.IsValid));
That will only include items where at least one of the values IsValid
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With