David Waters
David Waters

Reputation: 12028

What is an elegant way to convert IDictionary<string, object> to IDictionary<string, string>

I have a method I am not happy with, can you please show me how to do this better.

public Foo WithBar(IDictionary<string, object> parameters) {
    var strStrDict = new Dictionary<string, string>(parameters.Count);
    foreach(var pair in parameters)
    {
        strStrDict.Add(pair.Key, pair.Value != null ? pair.Value.ToString() : (string)null);
    }      
    // Call overload which takes IDictionary<string, string>  
    return this.WithBar(strStrDict);
}

This code works but I'm sure there is a nice linq'y way of doing this I am missing.

Upvotes: 3

Views: 2009

Answers (3)

Lasse Espeholt
Lasse Espeholt

Reputation: 17792

parameters.ToDictionary(k => k.Key, v => Convert.ToString(v.Value))

Convert.ToString() returns null on null-values which you would expect.

Update:

Convert.ToString(object) returns String.Empty but Convert.ToString(string) returns null. Unfortunately, that is not what you need. Weird definition in my opinion :-/

Upvotes: 4

Achim
Achim

Reputation: 15722

parameters.ToDictionary(p => p.Key, p => p.Value.ToString())  // out of my head

Upvotes: -1

Mark Cidade
Mark Cidade

Reputation: 100007

parameters.ToDictionary(k=>k.Key, v=>v.Value!=null?v.Value.ToString():(string)null);

Upvotes: 8

Related Questions