Home > OS >  how to use TyrGet pattern with default value to get everything done in one line
how to use TyrGet pattern with default value to get everything done in one line

Time:12-19

let's say we have the following code which is the most standard code to achieve the purpose:

// iterate each key value pairs in a Dictionary

string value;
if (!kvp.TryGetValue("MyKey", out value))
   value= "default";

but I want to do everything in one line, which is:

string newValue = kvp.TryGetValue("MyKey", out string value) ? value : "default";

// `value` is null if the key is not found, newValue is "default" which I can use
// but I don't want to use a new string variable `newValue`,
// I want "default" to be assigned to `value` variable

I also don't want to use any if statement such as:

if(!kvp.TryGetValue("MyKey", out string value)) value = "default" ;
// it is two statement technically

I can write a wrapper function to take the key as parameter but I feel that there must be another way to do it.

and I acknowledge that there is a GetValueOrDefault like kvp.GetValueOrDefault("MyKey", "default"), but what I really want to do is

kvp.TryGetValue("MyKey", out string value) ? value : value = "default";  // code doesn't compile, you get the idea

so is it a way to do everything in one line?

CodePudding user response:

You can write your own extension to get default value. Not sure why kvp if you can use dictionary...


public static bool TryGetValueOrDefault(this IDictionary<string, string> d, string key, string def, out string v)
{
    if (d.ContainsKey(key))
    {    
        v = d[key];
        return true;
    }

    v = def;
    return false;
}


. . . . . 
if (myDict.TryGetValueOrDefault("key", "someDefVal", out string retVal))
{
     // do something for found value
}
else
{
    // do something when value is not found
}


DoSomethingWithYourValue(retVal);


Or just forget about Try part and do


public static string GetDictValueOrDefault(this IDictionary<string, string> d, string key, string def).....

var ret = GetDictValueOrDefault("key", "someDefVal")
DoSomethingWithYourValue(ret);

CodePudding user response:

You can declare the value variable as a result of the ternary expression:

string value = kvp.TryGetValue("MyKey", out value) ? value :  "default";

Other possibilities:


You can use this syntax

if(!kvp.TryGetValue("MyKey", out string value)) value = "default" ;

When the result of TryGetValue is false, assign the default value.


When available (in .net Core 2 and higher), you can also use the GetValueOrDefault extension method:

string value = kvp.GetValueOrDefault("MyKey", "default");

Or write that extension method yourself:

public static class CollectionExtensions
{
    public static T2 GetValueOrDefault<T1, T2>(IDictionary<T1, T2> dict, T1 key, T2 defaultValue)
    {
        if (dict.TryGetValue(key, out T2 value)) value = defaultValue;
        return value;
    }
}
  • Related