2010-08-09 103 views
2

這裏是環我到目前爲止C# - 如何產生字符串「和」在正確的位置

foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>()) 
       { 
        if (chk.Checked) 
        { 
         //Code goes here 
        } 
       } 

的複選框都有的星期幾文本值。星期一,星期二等。

我想最終的結果是一個字符串,看起來像「星期一,星期二和星期五」取決於是否檢查框。

循環將更改布爾值,以便知道是否至少選中了一個複選框。這將被用在if語句之後,所產生的字符串將被顯示,因此如果沒有被選中,則不會顯示任何字符串。我認爲這意味着如果字符串有幫助,那麼字符串看起來無關緊要。

我希望我已經清楚。如果你需要更多細節,請詢問。

預先感謝您。


當前代碼:

string days = "*"; 
     foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>()) 
     { 
      if (chk.Checked) 
      { 
       days += "#" + chk.Text; 
      } 
     } 

     days = days.Insert(days.LastIndexOf('#'), " and "); 
     days = days.Remove(days.LastIndexOf('#'), 1); 
     days = days.Replace("#", ", "); 
     days = days.Replace("* and ", ""); 
     days = days.Replace("*, ", ""); 

有人能看到什麼錯呢?

+0

我記得在什麼地方[埃裏克斯有這樣的事情博客](http://blogs.msdn.com/b/ericlippert/),但我找不到它。 (這是一個挑戰,你應該發表你的答案作爲評論) – Oliver 2010-08-09 14:18:56

回答

3

我能想到的最簡單的方法是將foreach更改爲for循環。我目前沒有打開IDE,因此我無法仔細檢查控制器,但是一旦您有了List<CheckBox>,您就可以使用(不必要,只是更簡單一些),最終可以結束喜歡的東西:

//ckBoxes is our List<CheckBox> 
for(int i = 0; i < ckBoxes.Count; i++) 
{ 
    StringBuilder listBuilder = new StringBuilder; 
    if(i == ckBoxes.Count -1) 
    { 
    listBuilder.Append("and " + dayOfWeek) 
    } 
    else listBuilder.Append(dayOfWeek + ", "); 
} 

這是非常,非常粗糙,而且需要大量的清洗然後再使用它,但它應該把你一個可行的路徑上。

+0

你甚至不應該真的需要一個列表。您可以使用Linq在單一查詢中獲取IQueryable或類似構造,以獲得您需要的計數。 – 2010-08-09 14:51:38

+0

是的,我提到過。出於某種原因,我發現清單工作更容易。這可能是因爲每次我做了類似的事情時,我最終都需要一個List ,所以在開始時將它放在列表中更容易。 – AllenG 2010-08-09 14:54:10

0

使其成爲循環將跟蹤所有需要顯示用戶的日子(進入List或其他)。然後,在循環之後,使用string.Join將第一個N-1項目與「,」和第二個字符串合併。使用「and」加入最後一個項目。

0

最簡單的方法是有兩個循環。第一個建立一個檢查控制列表。然後遍歷你剛剛構建的列表並執行字符串生成器命令。

List<CheckBox> checked = new List<CheckBox>(); 
foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>()) 
{ 
    if (chk.Checked) 
    { 
     checked.Add(chk); 
    } 
} 
for(int i = 0; i < checked.Count; i++) 
{ 
    if (i == checked.Count-1)) 
    { 
     //write for last element 
    } 
    else 
    { 
     //write for all other elements 
    } 
} 
+0

-1:2循環不是必需的,只會增加完成的工作。此外,除了填充列表以獲取計數之外,您不使用第一個循環來完成任何操作。有更簡單的方法來實現這一點。 – 2010-08-09 14:50:14

+0

大部分提供的解決方案都是通過使用爲您構建列表的api隱藏第一個循環。我沒有寫出其他塊的主體,但它應該很明顯,涉及到獲取該列表的索引處的對象。 – unholysampler 2010-08-09 15:10:35

+0

你對所有人都是對的解決方案。它們和你的一樣循環。我已經標記了你的回答正確。雖然我認爲我的答案好多了。 – 2010-08-12 11:04:08

0

像這樣的東西應該工作:

var days = new List<string>(); 
foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>()) 
{ 
    if (chk.Checked) 
    { 
     days.Add(chk.Text); 
    } 
} 
string daysString = ""; 
if (days.Count == 1) 
{ 
    daysString = days[0]; 
} 
else if (days.Count > 1) 
{ 
    daysString = 
     string.Join(", ", days.Take(days.Count - 1)) + 
     " and " + 
     days[days.Count - 1]; 
} 
1

嘗試了這一點。

var days = gpbSchecule.Controls.OfType<CheckBox>() 
           .Where(x => x.Checked) 
           .Select(x => x.Text) 
           .ToArray(); 

這讓你包含數組只檢查天,你可以用它來確定是否「和」是必要的,並針對簡單的字符串的方法。

從這裏申請string.Join()的@Garo建議。

0

有點醜陋的解決方案,但應該工作。

string result = ""; 
string nextDay = null; 
foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>()) 
{ 
    if (nextDay != null) { 
     if (result.length() > 0) { 
     result += ", " + nextDay; 
     } else { 
     result = nextDay; 
     } 
     nextDay = null; 
    } 
    if (chk.Checked) 
    { 
     //Code goes here 
     nextDay = chk.text; // Your text here Monday, Tuesday, ... 
    } 
} 

if (nextDay != null) { 
    if (result.length() > 0) { 
    result += " and " + nextDay; 
    } else { 
    result = nextDay; 
    } 
    nextDay = null; 
} 
0
// change this into a collection of your checked group boxes 
    string[] threeStrings = new string[] { "Joe", "Jim", "Robert" }; 
    StringBuilder newString = new StringBuilder(); 

    // iterate over your array here - strings used to simplify example 
    for (int i = 0; i < threeStrings.Length; i++) 
    { 
     if (i < threeStrings.Length - 1) 
     { 
      newString.Append(threeStrings[i]); 
      newString.Append(", "); 
     } 
     else 
     { 
      newString.Append(" and "); 
      newString.Append(threeStrings[i]); 
     } 
    } 
    Console.WriteLine(newString.ToString()); 
0

這裏是另一種解決方案。我放了一些Init代碼來測試它。

private List<CheckBox> _checkBoxes; 

private void Test() 
{ 
    Init(); 

    List<CheckBox> checkedCheckBoxes = _checkBoxes.Where(cb => cb.Checked == true).ToList(); 
    StringBuilder str = new StringBuilder(); 
    string delimiter = String.Empty; 

    for (int i = 0; i < checkedCheckBoxes.Count; i++) 
    { 
     str.Append(delimiter); 
     str.Append(checkedCheckBoxes[i].Name); 

     if (i != checkedCheckBoxes.Count) 
     { 
      if (i == checkedCheckBoxes.Count - 2) 
       delimiter = " and "; 
      else 
       delimiter = ", "; 
     } 
    } 

    Console.WriteLine(str.ToString()); 
    Console.ReadLine(); 
} 

private void Init() 
{ 
    _checkBoxes = new List<CheckBox>(); 

    string[] days = new string[7] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; 
    Random r = new Random(); 

    foreach (string day in days) 
    { 
     CheckBox cb = new CheckBox(); 
     cb.Name = day; 
     cb.Checked = Convert.ToBoolean(r.Next(0, 2)); 
     _checkBoxes.Add(cb); 
    } 
} 
0

我投AllenG但你可以這樣來做太:

// First build a string of days separated by a coma 
string days = String.Empty; 
foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>()) 
{ 
    if (chk.Checked) 
    { 
     if (!String.IsNullOrEmpty(days)) 
      days += ", "; 
     days += chk.Text;    
    } 
} 

// Then replace the last coma with "and"    
int lastComaIndex = days.LastIndexOf(','); 
if (lastComaIndex >= 0) 
    days = days.Substring(0, lastComaIndex) + " and " + days.Substring(lastComaIndex + 2); 
0

這是我對此採取:

var darr = (from checkbox in gpbSchecule.Controls.OfType<CheckBox>() 
      where checkbox.Checked 
      select checkbox.Text) 
      .ToArray(); 

string days = ""; 
if (darr.Length > 0) 
{ 
    days = string.Join(", ", darr.Take(darr.Length - 1)); 
    if (darr.Length > 1) 
     days += " and "; 
    days += darr[darr.Length - 1]; 
} 
相關問題