Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dictionary from another dictionary using LINQ

Tags:

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.

like image 314
Bitmask Avatar asked Aug 15 '11 21:08

Bitmask


People also ask

What is ac dictionary?

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.

When to use dictionary in C#?

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.


1 Answers

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.

like image 95
StriplingWarrior Avatar answered Sep 29 '22 12:09

StriplingWarrior