Operations with Numbers in Redis Using C#

Moving On to Operations with Numbers

Welcome back! Now that you've learned how to work with numbers in Redis using C#, it's time to build on that knowledge and explore some basic operations with these numbers. This lesson will show you how to perform operations like incrementing, decrementing, and modifying numeric values directly in Redis.

What You'll Learn

In this lesson, you will learn how to:

  1. Increment and decrement numeric values.
  2. Modify numeric values using operations such as increments by a floating point.

Code Example

Here's the code snippet that we'll be working with:

using System;
using StackExchange.Redis;

class RedisNumberOperations
{
    static void Main()
    {
        // Connect to Redis
        ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
        IDatabase db = redis.GetDatabase();

        // Setting and getting string values
        db.StringSet("count", 5);
        db.StringSet("completion_rate", 95.5);
        db.StringSet("duration", 0);  // Ensure 'duration' is set initially

        db.StringDecrement("count");
        db.StringIncrement("completion_rate", 1.5);
        db.StringIncrement("duration");

        int count = (int)db.StringGet("count");
        double completionRate = (double)db.StringGet("completion_rate");
        int duration = (int)db.StringGet("duration");

        Console.WriteLine($"Course count: {count}");  // Output: Course count: 4
        Console.WriteLine($"Completion rate: {completionRate}");  // Output: Completion rate: 97.0
        Console.WriteLine($"Duration: {duration}");  // Output: Duration: 1
    }
}

Let's Break It Down

  • After setting initial values for count, completion_rate, and duration, we perform various operations:
    • StringDecrement("count") decreases the value of count by 1. In C#, you can also provide an additional parameter to specify the decrement value: db.StringDecrement("count", 2) will decrement count by 2. Note that StringDecrement can only be used on numeric values.
    • StringIncrement("completion_rate", 1.5) increments completion_rate by 1.5. This method can be applied to integer and floating-point values, allowing flexibility.
    • StringIncrement("duration") increases the duration by 1. Similar to decrementing, you can specify the increment value: db.StringIncrement("duration", 5) will increment duration by 5.
  • Finally, we retrieve the values and convert them to the required data type for proper display.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal