开发者

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

开发者 https://www.devze.com 2023-02-27 04:48 出处:网络
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) {

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
0

精彩评论

暂无评论...
验证码 换一张
取 消