views:

192

answers:

1

Something very basic seems to be escaping me.

Dim foo As New Dictionary(Of String, String)
foo.Add("key", Nothing)
foo.Add("key2", "something")

I wish to get a IDictiorany(Of String, String) back, with only elements that have a non empty value. I thought this would do it:

foo.Where(Function(x) Not String.IsNullOrEmpty(x.Value))

But that ends up being the wrong type. Adding:

.ToDictionary(Function(x) x.Key)

Doesn't help any either. Any tips?

+2  A: 

Ah... Answered my own question. Will leave this up just in case it is of any use to someone else.

Dim foo As Dictionary(Of String, String)
foo.Add("k1", Nothing)
foo.Add("k2", "something")

Dim IDictionary(Of String, String) res = foo _
    .Where(Function(x) Not String.IsNullOrEmpty(x.Value)) _
    .ToDictionary(Function(x) x.Key, Function(y) y.Value)
Daniel
Are you creating and filtering the dictionary in the same scope? If you are, you can use an anonymous type for the creation, which makes filtering and turning it into a dictionary much cleaner.
Daniel Schaffer