3

Possible Duplicate:
Is there an easy way to return a string repeated X number of times?

In Python you can multiply sequences like this

fivespaces= ' ' * 5

Is there any built-in equivalent for this in C#? (without operator overloads or class extensions)

Community
  • 1
  • 1
  • 1
    @AhmadMageed -- I'm not sure that I agree that this is a duplicate. As I see it, strings are just an example. python has other sequence types too (like a list): `five_spaces_in_a_list = [' ']*5` – mgilson Sep 26 '12 at 12:31

1 Answers1

5

If it's just a string then you can return multiples by passing in a count to string()

var fivespaces = new string(" ", 5);

In the case where you want a collection of something else like a custom type, you can use Enumerable.Repeat to get a collection:

var items = Enumerable.Repeat(new SomeModel(), 5);

Jamie Dixon
  • 49,653
  • 18
  • 119
  • 157
  • thanks, worked with single quotes :) –  Sep 26 '12 at 12:32
  • The 2nd example would also be useful if someone wanted to use sequence multiplication on an Array/List so thanks. –  Sep 26 '12 at 12:39
  • @k7ypt: Remember to accept the answer. – Tim Schmelter Sep 26 '12 at 12:52
  • I don't agree with the close as duplicate. The other thread only covers string concatenation. The following would also count as a sequence multiplcation. s=[1,2,3,4,5] *5; –  Jan 07 '13 at 12:32
  • The `String` constructor example doesn't compile. The only `String` constructor overload that repeats a value takes a single `char` (inside single quotes, not doubles as in the answer). There is no overload taking and repeating a `string`. – Bob Sammers Aug 21 '18 at 13:44