Is there a way to convert RedisValue[] to string[]?

Jay Stevens picture Jay Stevens · Oct 1, 2014 · Viewed 7.7k times · Source

I have an array RedisValue[] returned from the StackExchange.Redis client. I want to take each of the values (which are actually JSON strings) in the array and join them together to get a valid JSON string that I can return to the client.

Here's what I want to do...

var results = redis.HashGet("srch", ArrayOfRedisKeys[]);

string returnString = "[" + string.Join(results, ",") + "]";

However, this doesn't work because results is an array of RedisValue not an array of string. Is there a straight-forward and performant way to do this other than just iterating the RedisValue array?

Answer

Marc Gravell picture Marc Gravell · Oct 1, 2014

Not currently, but I have just pushed the following extension method into ExtensionMethods.cs:

    static readonly string[] nix = new string[0];
    /// <summary>
    /// Create an array of strings from an array of values
    /// </summary>
    public static string[] ToStringArray(this RedisValue[] values)
    {
        if (values == null) return null;
        if (values.Length == 0) return nix;
        return Array.ConvertAll(values, x => (string)x);
    }

So: in the next build, you can just use results.ToStringArray(). Until then, you could just copy the above locally.