web analytics

Equivalent of Oracle DECODE function in C#

Options

codeling 1602 - 6666
@2017-04-19 11:18:53

Oracle PL/SQL has a built-in function DECODE:

decode( expression , search , result [, search , result]... [, default] )

The following C# code demonstrates the similar functionality.

public static TOutput Decode<TInput, TOutput>(TInput expression, params Tuple<TInput, TOutput>[] searchResultPairs)
    => DecodeWithDefault(expression, default(TOutput), searchResultPairs);

public static TOutput DecodeWithDefault<TInput, TOutput>(TInput expression, TOutput defaultValue, params Tuple<TInput, TOutput>[] searchResultPairs)
{
    foreach(var searchResultPair in searchResultPairs)
    {
        if ((expression == null && searchResultPair.Item1 == null)
            || (expression != null && expression.Equals(searchResultPair.Item1)))
        {
            return searchResultPair.Item2;
        }
    }

    return defaultValue;
}

Sample usage:

Console.WriteLine(Decode(5, Tuple.Create(23, "twenty-three"), Tuple.Create(5, "five")));

Console.WriteLine(Decode(23, Tuple.Create(23, "twenty-three"), Tuple.Create(5, "five")));

Console.WriteLine(Decode(6, Tuple.Create(23, "twenty-three"), Tuple.Create(5, "five")));

Console.WriteLine(DecodeWithDefault(6, "not found", Tuple.Create(23, "twenty-three"), Tuple.Create(5, "five")));

Output:

five

twenty-three

not found

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com