簡體   English   中英

格式化字符串的輸出

[英]Formatting the output of a String

我是C#的新手。 我正在大學的一個單元中學習它。 我們已獲得一項分配任務,其中涉及我們必須使用Visual Studio工具箱中包含的各種組件來創建一個簡單的預訂應用程序。

UI具有一個ListBox ,該ListBox使用戶可以選擇將參加活動的人員的多個名稱。 用戶確認選擇后,所選項目將連接到String並在Label輸出。

這是我從ListBox獲取值的代碼

 protected void btnRequest_Click(object sender, EventArgs e)
{
    //Update the summary label with the details of the booking.
    n = name.Text;
    en = eventName.Text;
    r = room.SelectedItem.ToString();
    d = cal.SelectedDate.ToShortDateString();

    foreach (ListItem li in attendees.Items)
    {
        if (li.Selected)
        {
            people += li.Text + " ";
        }
    }


    confirmation.Text = r + " has been booked on " + d + " by " + n + " for " + en + ". " + people + " will be attending.";
}

下面是我的整個代碼:

public partial class _Default : System.Web.UI.Page
{
    //Variables
    public TextBox name;
    public TextBox eventName;
    public Label confirmation;
    public DropDownList room;
    public Calendar cal;
    public Button btn;
    public ListBox attendees;

    //Booking variables - store all information relating to booking in these variables
    public String n; //name of person placing booking
    public String en; //name of event
    public String r; //room it will take place
    public List<String> att; //list of people attending
    public String d; //date it will be held on

    public String people;

    protected void Page_Load(object sender, EventArgs e)
    {
        //Get references to components
        name = txtName;
        eventName = txtEvent;
        room = droplistRooms;
        attendees = attendeelist;
        cal = Calendar1;
        btn = btnRequest;
        confirmation = lblSummary;

    }
    protected void btnRequest_Click(object sender, EventArgs e)
    {
        //Update the summary label with the details of the booking.
        n = name.Text;
        en = eventName.Text;
        r = room.SelectedItem.ToString();
        d = cal.SelectedDate.ToShortDateString();

        foreach (ListItem li in attendees.Items)
        {
            if (li.Selected)
            {
                people += li.Text + " ";
            }
        }


        confirmation.Text = r + " has been booked on " + d + " by " + n + " for " + en + ". " + people + " will be attending.";
    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        d = cal.SelectedDate.ToShortDateString();
    }

輸出是這樣的:

會議室2已由Jason Manford在2013年10月10日預訂為Comedy Gig。 Jack Coldrick Bill Gates Larry Page Jimmy Wales將出席。

不過,我想在參加活動的人的姓氏上加上和。 我將如何去做。 我需要使用List嗎?

非常感謝...

嘗試將所選項目復制到另一個集合中並使用一個簡單的計數器:

int counter = 1; // start at 1 so that the counter is in line with the number of items that the loop has iterated over (instead of 0 which would be better for indexing into the collection)

List<ListItem> selectedItems = new List<ListItem>();

foreach (ListItem li in attendees.Items)
{
    if (li.Selected)
    {
        selectedItems.Add(li);
    }
}

foreach (ListItem li in selectedItems)
{
    counter++;

    if (selectedItems.Count > 1 && i == selectedItems.Count) // check after the counter has been incremented so that only the last item triggers it
    {
        people += " and";
    }

    people += li.Text + " ";
}

正如一些人指出的那樣,您還應該考慮使用StringBuilder ,因為字符串在.Net中是不可變的,這意味着它們不能被修改。 每次將文本追加到字符串時,都會在幕后創建帶有新內容的新字符串,而舊字符串將被丟棄。 可以想象,如果列表中有很多名稱,那么最終可能會影響性能。 下面的例子:

List<ListItem> selectedItems = new List<ListItem>();

foreach (ListItem li in attendees.Items)
{
    if (li.Selected)
    {
        selectedItems.Add(li);
    }
}

StringBuilder sbPeople = new StringBuilder();
int counter = 1; // start at 1 so that the counter is in line with the number of items that the loop has iterated over (instead of 0 which would be better for indexing into the collection)

foreach (ListItem li in attendees.SelectedItems)
{
    counter++;

    if (selectedItems.Count > 1 && i == selectedItems.Count) // check after the counter has been incremented so that only the last item triggers it
    {
        sbPeople.Append(" and");
    }

    sbPeople.Append(li.Text);
    sbPeople.Append(" ");
}

StringBuilder文檔的引用: http : //msdn.microsoft.com/zh-cn/library/system.text.stringbuilder.aspx

var p = new List<string>() {"person1", "person2", "person3"};
string people;
if(p.Count == 1)
    people = p[0];
else
    people = string.Join(", ", p.Take(p.Count - 1)) + " and " + p[p.Count - 1]

為了更好地適合您的代碼,我將編寫如下內容(從注釋中間接建議):

var p = attendees.Items.OfType<ListItem>.Where(y => y.Selected).Select(y => y.Text).ToList();
var people = "";
if(p.Count == 1)
    people = p[0];
if(p.Count > 1)
    people = string.Join(", ", p.Take(p.Count - 1)) + " and " + p[p.Count - 1]

Confirmation.Text = string.Format("{0} has been booked on {1} by {2} for {3}. {4} will be attending", r, d, n, en, people);

您可以用這個替換您的foreach

var peopleList = new List<string>();

foreach (ListItem li in attendees.Items)
{
    if (li.Selected)
       peopleList.Add(li.Text);
}

var people = string.Join(",", list.Take(list.Count - 1));
people += list.Count > 1 ? " and " + list.Last() : list.Last();

為了使答案與您的問題保持一致,盡管我使用StringBuilder而不是附加字符串,但我將使其易於理解-我已經看到此方法處理大型字符串的速度更快。

var selectedPeople = new List<string>();

foreach (ListItem li in attendees.Items)
{

    if (li.Selected)
    {
        people.Add(li.Text);
    }

}
var sb = new StringBuilder();
if (selectedPeople.Count == 0)
{
    sb.Append("");
}
else
{
    for (var i = 0; i < selectedPeople.Count; i++)
    {
        if (i > 0)
        {
            sb.Append(" ");
            if (i == selectedPeople.Count)
            {
                sb.Append("and ");
            }
        }
        sb.Append(selectedPeople[i]);
    }
}


...

confirmation.Text = r + " has been booked on " + d + " by " + n + " for " + en + ". " + sb.ToString() + " will be attending.";

我建議您研究另一個建議使用SelectedItems的答案,以防止必須執行第一個循環。

var selectedPeople = list.Items.OfType<ListItem>().Where(c => c.Selected).Select(c => c.Text).ToList();
string people;
if (selectedPeople.Count == 1)
    people = selectedPeople[0];
else
    people = string.Join(", ", selectedPeople.Take(selectedPeople.Count - 1)) 
                + " and " + selectedPeople[selectedPeople.Count - 1];

暫無
暫無

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

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