Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repeat string with LINQ/extensions methods [duplicate]

Tags:

c#-4.0

Just a curiosity I was investigating.

The matter: simply repeating (multiplying, someone would say) a string/character n times.
I know there is Enumerable.Repeat for this aim, but I was trying to do this without it. LINQ in this case seems pretty useless, because in a query like

from X in "s" select X  

the string "s" is being explored and so X is a char. The same is with extension methods, because for example "s".Aggregate(blablabla) would again work on just the character 's', not the string itself. For repeating the string something "external" would be needed, so I thought lambdas and delegates, but it can't be done without declaring a variable to assign the delegate/lambda expression to.
So something like defining a function and calling it inline:

( (a)=>{return " "+a;} )("a");  

or

delegate(string a){return " "+a}(" ");  

would give a "without name" error (and so no recursion, AFAIK, even by passing a possible lambda/delegate as a parameter), and in the end couldn't even be created by C# because of its limitations.
It could be that I'm watching this thing from the wrong perspective. Any ideas?
This is just an experiment, I don't care about performances, about memory use... Just that it is one line and sort of autonomous. Maybe one could do something with Copy/CopyTo, or casting it to some other collection, I don't know. Reflection is accepted too.

like image 621
lunadir Avatar asked Dec 13 '12 16:12

lunadir


1 Answers

To repeat a character n-times you would not use Enumerable.Repeat but just this string constructor:

string str = new string('X', 10);

To repeat a string i don't know anything better than using string.Join and Enumerable.Repeat

string foo = "Foo";
string str = string.Join("", Enumerable.Repeat(foo, 10));

edit: you could use string.Concat instead if you need no separator:

string str = string.Concat( Enumerable.Repeat(foo, 10) );
like image 155
Tim Schmelter Avatar answered Sep 28 '22 17:09

Tim Schmelter