score:9

Accepted answer

for your interviewer

string output = new string(input.select(ch => ch == '2' ? '0' : ch).toarray());

i think intend was to see if you understand that string could be treated as sequence of characters. interviews often have questions not related to real-life programming. i personally hate questions about inheritance tree with new modifiers.

score:0

string strinput = "21212121";

char from = '2';
char to = '0';

var stroutput = new string(strinput.select(c => c.equals(from) ? to : c)
                                   .toarray());

console.writeline(stroutput);

score:1

for changing a single character you can use the overload of replace that takes char arguments:

string s = "21212121";
s = s.replace('2', '0');

this is likely to be slightly more efficient than the overload that accept strings.


if you absolutely have to use linq for some reason, then you can do this:

s = new string(s.select(c => c == '2' ? '0' : c).toarray());

but you shouldn't do this in production code. it's harder to read and less efficient than string.replace.

score:12

why you need to do it with linq, simple string.replace should do the trick.

string str = "21212121".replace("2","0");

edit: if you have to use linq then may be something like:

string  newstr = new string(str.select(r => (r == '2' ? '0' : r)).toarray());

Related Query

More Query from same tag