0
\$\begingroup\$

I have strings named like this:

list_1 = {"a", "b", "c"};
list_2 = {"v", "t", "d"};
list_3 = {"e", "a", "b"};
..
list_100 = {"g", "q", "z"};

and I have a variable:

int counter;

and I have string[] myList; which I define as below:

if (counter==1){
   myList = list_1;
} 
else if (counter==2){
   myList = list_2;
} 
else if (counter==3){
   myList = list_3;
} 
...

else {
    myList = list_100;
}

Is there a way to shorten this code, so that if score == i, then I can assign myList = list_i?

ty so much!

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

This looks like you want an array of arrays, also called a jagged array (since each row could have its own length):

string[][] allLists = new string[][]{
   new string[]{"a", "b", "c"},
   new string[]{"d", "e", "f"},
   ...
};

string[] myList = allLists[counter - 1];

Or you could do it with a two-dimensional array,

string[,] table = new string[,]{
  {"a", "b", "c"},
  {"d", "e", "f"},
  ...
}

And then replace any access of myList[i] with table[counter - 1, i] to index both your desired row and column.

This is very beginner C#, so you might want to work through some more introductory tutorials for the language to get familiar with these fundamentals.

\$\endgroup\$
0
\$\begingroup\$

You could use a List<T> for that (not sure about the exact syntax in c#):

List<string[]> lists = new List<string[]>();
lists.Add( new string[]{"a", "b", "c"});
lists.Add( new string[]{"v", "t", "d"} );
lists.Add( new string[]{"e", "a", "b"} );
..
lists.Add( new string[]{"g", "q", "z"} );

then

string[] myList;
if ( counter >= 1 && counter <= lists.Count )
    myList = lists[counter - 1];
else 
    myList = lists[lists.Count - 1]

You could also achieve this with a Dictionary<TKey,TValue> (again, not sure about the exact syntax in c#):

Dictionary<int, string[]> scoresTexts = new Dictionary<int, string[]>();

scoresTexts.Add( 1, new string[]{"a", "b", "c"});
scoresTexts.Add( 2, new string[]{"v", "t", "d"} );
scoresTexts.Add( 3, new string[]{"e", "a", "b"} );
..
scoresTexts.Add( 100, new string[]{"g", "q", "z"} );

then:

string[] myList;
if (!scoresTexts.TryGetValue(score, out myList))
    myList = scoresTexts[100];

In any case, I think DMGregory's answer suggests approaches that are more efficient than those proposed here.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .