HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

switch to create number of symbols

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
switchnumbercreatesymbols

Problem

This code shows an icons from the Segoe MDL2 Assets font, depending on the number in a variable. However, I'm sure there is a more elegant way of doing this.

switch (numberOfPeople)
{
    case 0:
        return "";
    case 1:
        return "\xE77B";
    case 2:
        return "\xE77B \xE77B";
    case 3:
        return "\xE77B \xE77B \xE77B";
    case 4:
        return "\xE77B \xE77B \xE77B \xE77B";
    default:
        break;

}

Solution

I'm sure there is a more elegant way of doing this.

Indeed. With LINQ. You can generate multiple instances with Repeat and join them with string.Join

var symbol = "\xE77B";
var separator = " ";
var count = 5
var result = string.Join(separator, Enumerable.Repeat(symbol, count));


This will work with count = 0 too and generate an empty string.

Code Snippets

var symbol = "\xE77B";
var separator = " ";
var count = 5
var result = string.Join(separator, Enumerable.Repeat(symbol, count));

Context

StackExchange Code Review Q#158022, answer score: 5

Revisions (0)

No revisions yet.