Search code examples
c#stringlinqstringbuilder

How to change a string content according to another string with LINQ C#


In my homework, I've got a mission to replicate the enigma machine. so I'm building the reflector part. The reflector has a configuration like this:

YRUHQSLDPXNGOKMIEBFZCWVJAT

and the task is for every character in a string, I need to replace it with the corresponding character in the configuration position, assuming the text would contain only uppercase letters. for example, let's say I've got an input like this:

ABCXYZ

so the answer would be "YRUJAT"

so I made a function like this:

public string GetReflectedString(string msg)
{
    StringBuilder answer = new StringBuilder();
    foreach (char item in msg)
    {
        answer.Append(m_configuration[Helper.ABC.IndexOf(item.ToString().ToUpper())]);
    }
    return answer.ToString();
}

but I have the feeling this could be made better with LINQ functions. can anybody help?


Solution

  • I'd not use the words better necessarily but maybe uses less lines of code, here is an implementation using linq:

    var result = new string(msg.Select(c => m_configuration[Helper.ABC.IndexOf(c)]).ToArray());
    

    Badically, replace the foreach with a projection (.Select) and then place all of it as an input for the string constructor.

    As a short standalone example:

    var configuration = "YRUHQSLDPXNGOKMIEBFZCWVJAT";
    var abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    var input = "ABCXYZ";
    var result = new string(input.Select(c => configuration[abc.IndexOf(c)]).ToArray());
    Console.WriteLine(result);    // YRUJAT