簡體   English   中英

選中逗號分隔列表的復選框,在C#末尾帶有“和”字樣

[英]Checked checkboxes to comma separated list with word “and” at the end in C#

我在WinForms面板中有一些復選框。 選中復選框后,我想創建一個以逗號分隔的列表,但在最后一個復選框文本值前面加上“和”。

這是我目前擁有的代碼...它是從所有復選框共享的單個事件處理程序執行的:

    string checkboxes = " ";
    foreach (Control c in MyPanel.Controls)
    {
        if (c is CheckBox && (c as CheckBox).Checked)
            checkboxes += (c as CheckBox).Text;
    }
    checkboxes = string.Join(", ", checkboxes.Take(checkboxes.Count() - 1)) + (checkboxes.Count() > 1 ? " and " : "") + checkboxes.LastOrDefault();
    Console.WriteLine(checkboxes + "are checked");

我有以下復選框:

_Item A
_Item B
_Item C
_Item D

例如,如果檢查了項目A和B,我希望它吐出“ 檢查項目A和B ”。

如果檢查項目A,B和D ......“檢查項目A,項目B和項目D

但是,使用我當前的代碼,它正在執行類似於此的操作:

檢查I,t,e,m,A,I,t,e,m,B,I,t,e,m和D.

如果有人能指出我正確的方向,我會非常感激!

嘗試這個:

string checkboxes = " ";
foreach (Control c in MyPanel.Controls)
{
    if (c is CheckBox && (c as CheckBox).Checked)
        checkboxes += (c as CheckBox).Text.Split().Last();
}
checkboxes=String.Concat(checkboxes.OrderBy(c => c);
checkboxes = string.Join(", ", checkboxes.Take(checkboxes.Count() - 1)) + (checkboxes.Length > 1 ? " and " : "") + checkboxes.LastOrDefault();
if (checkboxes.Length>1)
     checkboxes = checkboxes.Remove(0, 2);
Console.WriteLine("Items " + checkboxes + " are checked");

這是使用LINQ和String.Join的窮人實現。 這首先將“和”添加到最后一項,然后簡單地將結果連接在一起以形成逗號分隔的列表:

//get a list of the text of the checked checkboxes
var checkedNames = MyPanel.Controls.OfType<CheckBox>().Cast<CheckBox>()
    .Where(c => c.Checked).Select(c => c.Text).ToList();

//boundary cases
if(checkedNames.Count == 0)
    return "Nothing is checked";
else if(checkedNames.Count == 1)
    return checkedNames[0] + " is checked";    

//add an "and" to the last one
checkedNames[checkedNames.Count - 1] = "and " + checkedNames[checkedNames.Count - 1];

//join them up into a comma-separated list
return String.Join(" ,", checkedNames) + " are checked";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM