Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

string - how to declare multiple variable names with loop in c#

How can I declare multiple variable names within a loop in c#

Is there any way to do declare the n strings by loop

i don't have to use array..please if this can be done without array then please tell it will be very helpful to me

For example:-

String st1 = "";
String st2 = "";
String st3 = "";
String st4 = "";
String st5 = "";

If there is any way to do this then please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, if I am interpreting your question right, you can declare an array or list, then initialize these elements in a loop

For example (array) (if you want a fix number of elements):

int n = 10; // number of strings

string[] str = new string[n]; // creates a string array of n elements

for (int i = 0; i < n; i++) {
    str[i] = ""; // set the value "" at position i in the array
}

(list) (if you don't want a fix number of elements)

using System.Collections.Generic;

...
int n = 10;
List<string> str = new List<string>(); // creates a list of strings
// List<string> str = new List<string>(n) to set the number it can hold initially (better performance)

for (int i = 0; i < n; i++) {
    list.Add(""); // if you've set an initial capacity to a list, be aware that elements will go after the pre allocated elements
}

list[0] = "hello world"; // how to use a List
list[list.Count - 1] = "i am the last element"; // list.Count will get the total amount of elements in this list, and we minus 1 to fix indexing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...