web analytics
Equivalent of Oracle DECODE function in C# Options
codeling
Posted: Wednesday, April 19, 2017 11:18:53 AM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 770
Points: 3234

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

Sponsor
Posted: Wednesday, April 19, 2017 11:18:53 AM
 
Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.