Working with Lists and Sets
Redis provides powerful data structures for working with lists and sets of data.
Lists
Lists in Redis are ordered collections of strings. They are useful for implementing queues, stacks, and maintaining an ordered collection of data.
To work with lists in Redis, you can use the following commands:
ListRightPush
: Add an element to the right end of a listListLeftPush
: Add an element to the left end of a listListRange
: Get all elements in a list
Here's an example of using lists in Redis with C#:
TEXT/X-CSHARP
1const string playersKey = "basketball_players";
2
3// Add players to the list
4db.ListRightPush(playersKey, "Kobe Bryant");
5db.ListRightPush(playersKey, "Michael Jordan");
6db.ListRightPush(playersKey, "LeBron James");
7
8// Get all players
9RedisValue[] players = db.ListRange(playersKey);
10
11// Print all players
12foreach (RedisValue player in players)
13{
14 Console.WriteLine(player);
15}
Sets
Sets in Redis are unordered collections of unique strings. They are useful for maintaining a collection of distinct values.
To work with sets in Redis, you can use the following commands:
SetAdd
: Add an element to a setSetMembers
: Get all members of a set
Here's an example of using sets in Redis with C#:
TEXT/X-CSHARP
1const string playersKey = "basketball_players";
2
3// Add players to the set
4db.SetAdd(playersKey, "Kobe Bryant");
5db.SetAdd(playersKey, "Michael Jordan");
6db.SetAdd(playersKey, "LeBron James");
7
8// Get all players
9RedisValue[] players = db.SetMembers(playersKey);
10
11// Print all players
12foreach (RedisValue player in players)
13{
14 Console.WriteLine(player);
15}
xxxxxxxxxx
15
const playersKey = "basketball_players";
// Add players to the list
db.ListRightPush(playersKey, "Kobe Bryant");
db.ListRightPush(playersKey, "Michael Jordan");
db.ListRightPush(playersKey, "LeBron James");
// Get all players
RedisValue[] players = db.ListRange(playersKey);
// Print all players
foreach (RedisValue player in players)
{
Console.WriteLine(player);
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment