I have a two-dimensional char array declared with four strings.
private static string string1 = "abcde";
private static string string2 = "ABCDE";
private static string string3 = "12345";
private static string string4 = "67890";
public string selectChars(bool includeOne, bool includeTwo, bool includeThree, bool includeFour)
{
char[][] charGroups = new char[][]
{
string1.ToCharArray(),
string2.ToCharArray(),
string3.ToCharArray(),
string4.ToCharArray()
};
}
I want to declare and initialize the array such that the string add is conditional based on four bool flags. For example, if includeOne and includeThree are true, I want to end up with a charGroup[2][5] having used string1 and string 开发者_StackOverflow中文版3.
(This is existing code where I don't want to radically change the rest of the code. if I can conditionally declare the array in that block, I'm done.)
The manner you want is like a list, so it's better implement it by list and then return an array by ToArray
:
public string selectChars(bool includeOne, bool includeTwo, bool includeThree, bool includeFour)
{
List<char[]> chars = new List<char[]>();
string string1 = "";
if (includeOne)
chars.Add(string1.ToCharArray());
if(includeTwo) ....
char[][] charGroups = chars.ToArray();
}
I don't have the VM going but I think this should work...
private static string string1 = "abcde";
private static string string2 = "ABCDE";
private static string string3 = "12345";
private static string string4 = "67890";
public string selectChars(bool includeOne, bool includeTwo, bool includeThree, bool includeFour)
{
char[][] charGroups = new char[][]
{
include1 ? string1.ToCharArray() : new char[0],
include3 ? string2.ToCharArray() : new char[0],
include3 ? string3.ToCharArray() : new char[0],
include4 ? string4.ToCharArray() : new char[0]
};
}
If all you want to do is include the string as a character array if their respective flag is set then I think this will do the trick. It is using the conditional operator to include the left side of ':' (if includeX is true) otherwise include the right side.
1) Count up how many strings need to be added (how many of the flags are true).
2) char[][] charGroups = new char[count][];
(might need to be char[][count]
; I'm operating on very little sleep)
3) Init an index to 0; for each flag, if it's set, put the appropriate char[]
into that index, and increment the index.
But why, oh why are you taking the String
s apart into char[]
s? The String
class is your friend. It wants to make your life easier.
精彩评论