Click here to Skip to main content
15,887,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to Produces a sequence of strings representing the string version of a sequence of integers using LINQ Select or SelectMany keyword
Thank You in advance!

I need the output to be:
"five",
"four",
"one",
"three",
"nine",
"eight",
"six",
"seven",
"two",
"zero",

update:
Solved Thank to Maciej Los

int[] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0};
            string[] strings = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

            IEnumerable<string> stringSequence = numbers.Select(x => strings[x]).ToList();

            return stringSequence;


What I have tried:

public static void Main(string[] args)
        {
            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

            IEnumerable<string> stringSequence = numbers.Select((n, index) => n.ToString == strings[index]); // I know this is wrong but can't figure out how to do it correctly.

// I also tried: 
IEnumerable<string> stringSequence = numbers.Select(x => x.ToString());


Console.WriteLine(stringSequence);
    }
Posted
Updated 28-Feb-22 4:03am
v4
Comments
Luc Pattyn 28-Feb-22 10:20am    
Sorry, in the line
IEnumerable<string> stringSequence = numbers.Select(x => strings[x]).ToList();

calling ToList() does not make any sense as you are assigning to stringSequence which is an IEnumerable, and your numbers.Select() already is an IEnumerable, so all memory and CPU cycles spent to ToList() are wasted.

:)
PIEBALDconsult 28-Feb-22 10:26am    
You could also look into using an enum.

1 solution

I'd use Dictionary[^] object:

C#
Dictionary<int, string> WordNum = new Dictionary<int, string>();
WordNum.Add(0, "zero");
WordNum.Add(1, "one");
WordNum.Add(2, "two");
WordNum.Add(3, "three");
WordNum.Add(4, "four");
WordNum.Add(5, "five");
WordNum.Add(6, "six");
WordNum.Add(7, "seven");
WordNum.Add(8, "eight");
WordNum.Add(9, "nine");

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };


var result = numbers.Select(x=> WordNum[x]).ToList();
 
Share this answer
 
Comments
LuckyChloe 28-Feb-22 10:00am    
Thank you. Will take a look at Dictionary concept.
Maciej Los 28-Feb-22 10:06am    
You're very welcome. Good luck!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900