Click here to Skip to main content
15,066,156 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
My string is string data = "good"
i want to make a array of 50 items or list<string>; that contains same string data in it .
how can i make it dynamically ?? i Want to make an array of items in it , and store it in another string .
Thanks in advance ..

What I have tried:

string data = "good"
string [] newdata = new string[];
Posted
Updated 27-Jun-21 21:55pm
v2
Comments
Ralf Meier 28-Jun-21 4:13am
   
If none of the given answers are matching to your issue you should think about the description of what you want to do.
Perhaps you should improve your question with much more information - for me it sounds that you want to have sub-items to your items ...?

Simplest way is a loop:
C#
string data = "good"
int items = 50;
string[] newdata = new string[items];
for (int i = 0; i < items; i++)
   {
   newdata[i] = data;
   }

Though what on earth you mean by "and store it in another string" I have no idea ...
   
v2
Comments
George Swan 28-Jun-21 1:10am
   
If you are using .NetCore you can do this
string data = "good";
string[] newdata = new string[50];
Array.Fill(newdata, data);
OriginalGriff 28-Jun-21 1:18am
   
It'll be in .NET 6 as well - but that's not released until November.
Richard Deeming 28-Jun-21 4:46am
   
The docs claim it's in .NET 5:
Array.Fill Method (System) | Microsoft Docs[^]
OriginalGriff 28-Jun-21 5:22am
   
It was early in the morning, I missed the "and other versions" bit. :O
Richard Deeming 29-Jun-21 6:08am
   
Of course, looking at the source[^], it's not doing anything clever. :)
OriginalGriff 29-Jun-21 6:53am
   
[CharitableMode]
It might compile to a single machine code instruction ... MOVSW perhaps?
[/CharitableMode]
Richard Deeming 29-Jun-21 6:58am
   
It's not marked for aggressive inlining, so even if the JIT could convert it to a single instruction, you'd probably still have the overhead of the method call. :)
CPallini 28-Jun-21 2:58am
   
There's an underscore too much. :-)
OriginalGriff 28-Jun-21 3:48am
   
Thanks - fixed.
Dunno where that came from ... :sigh:
Same question as How to add items to each elements of list<string> ?[^]. Please do not repost.
   

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