Add string to array only if data is available
I have some code that builds a string array using data from a form:
string[] var4 = new string[] {
"Issue=" + DropDownListIssue.SelectedItem.ToString(),
"SubIssue=" + DropDownListSubIssue.SelectedItem.ToString(),
"Layout=" + DropDownListLayout.SelectedItem.ToString()
};
This code adds all the elements to the array even if there is no data. For example, say the value of Issue is "Apple," but the other two dropdownlists are left blank. The resulting var4 would be this:
"Issue=Apple"
"SubIssue="
"Layout="
In this case, I would like var4 to be:
"Issue=Apple"
SubIssue and Layout are not added to the array as they are left blank. If they are filled 开发者_运维百科in, however, then they should be added to the array. Example:
"Issue=Apple"
"SubIssue=Dog"
"Layout=Square"
How can I write this to only add the string when it has a value?
You can do the following:
string[] possibleNulllVar4 = new string[] {
string.IsNullOrEmpty(DropDownListIssue.SelectedItem.ToString()) ? "Issue=" + DropDownListIssue.SelectedItem.ToString() : null,
string.IsNullOrEmpty(DropDownListSubIssue.SelectedItem.ToString()) ? "SubIssue=" + DropDownListSubIssue.SelectedItem.ToString() : null,
string.IsNullOrEmpty(DropDownListLayout.SelectedItem.ToString()) ? "Layout=" + DropDownListLayout.SelectedItem.ToString() : null
};
Edit: Ah, if you don't want any empty nodes, do the following afterward:
var var4 = possibleNulllVar4.Where(x => null != x).ToArray();
Easy!
List<string> list = new List<string>();
var str = DropDownListIssue.SelectedItem.ToString();
if (!string.IsNullOrEmpty(str))
list.Add("Issue=" + str);
str = DropDownListSubIssue.SelectedItem.ToString();
if (!string.IsNullOrEmpty(str))
list.Add("SubIssue=" + str);
str = DropDownListLayout.SelectedItem.ToString();
if (!string.IsNullOrEmpty(str))
list.Add("Layout=" + str);
string[] var4 = list.ToArray();
I'm on a phone so please forgive some of the grammar / spelling / code sample if it doesn't work as is...
But the generic idea is this:
Why not loop through a collection of those DropDown lists, if one has a selected value, add the value to the passed in array (or use an Arraylist.ToArray() or List.ToArray()) so yo udon't need to redim it. Each dropdown can have a argument/command on it, so you'd know which one you're dealing with:
Similar to (PSEUDO)
List<DropDowns> dropDowns = ...//Get your dropdowns into the list
foreach(dd in dropDowns)
{
if(dd.SelectedItem != null && d.SelectedIndex != -1 )
YourStringArray.Add(dd.CommandArgument + "=" + dd.SelectedValue);
}
Sorry - on phone so it might not "compile" but that's why I marked id pseduo. Doing a List<> and a Foreach isn't the most efficient, but it gets away from ugly massive if statements.
精彩评论