How to use tricks in combination of "IF" conditions?(C# ASP.NET)
I have four checkboxes in my form. I have string variable called "CheckedString". If i check the first checkbox "A" must be assigned to "CheckedString". If i select both first and second checkbox at a time. "AB" must be assigned to "CheckedString". If i select third and fourth checkbox "CD" must be assigned to "CheckedString"开发者_如何学JAVA.So that several combination exists. How to implement this in C sharp. Please help?
Pseudocode since my VS2008 is currently in a "hosed" state and I can't check:
string CheckedString = ""
if checkbox a is set:
CheckedString += "A"
if checkbox b is set:
CheckedString += "B"
if checkbox c is set:
CheckedString += "C"
if checkbox d is set:
CheckedString += "D"
Voila! There you have it. You simply append the value for each checkbox in order.
string result = String.Format("{0}{1}{2}{3}",
checkboxA.Checked ? "A" : string.Empty,
checkboxB.Checked ? "B" : string.Empty,
checkboxC.Checked ? "C" : string.Empty,
checkboxD.Checked ? "D" : string.Empty
);
string CheckedString = (cbxA.Checked ? "A" : "") +
(cbxB.Checked ? "B" : "") +
(cbxC.Checked ? "C" : "") +
(cbxD.Checked ? "D" : "");
Go with paxdiablo. For a more 'general' solution, you can do something like this in LINQ (assuming you have the checkboxes in an array):
var chars = Enumerable.Range(0, checkBoxes.Length) // 0, 1, 2, 3
.Where(i => checkBoxes[i].Checked) // 0, 2
.Select(i => (char)('A' + i)); // A, C
var myString = new string(chars.ToArray()); // "AC"
or, with a for-loop:
var sb = new StringBuilder();
for (int i = 0; i < checkBoxes.Length; i++)
{
if (checkBoxes[i].Checked)
sb.Append((char)('A' + i));
}
var myString = sb.ToString();
Here they way write in C# and using function (reusability):
string CheckedString = string.Empty;
CheckedString += AssignCheckBox(chkBoxFirst, "A");
CheckedString += AssignCheckBox(chkBoxSecond, "B");
CheckedString += AssignCheckBox(chkBoxThird, "C");
CheckedString += AssignCheckBox(chkBoxFourth, "D");
And the function is:
public string AssignCheckBox(CheckBox chk, string strSet)
{
return chk.Checked ? strSet : string.Empty;
}
精彩评论