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.
parameters.ToDictionary(k=>k.Key, v=>v.Value!=null?v.Value.ToString():(string)null);
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 :-/
parameters.ToDictionary(p => p.Key, p => p.Value.ToString()) // out of my head
精彩评论