最近看到string有join這個用法..還不錯用..介紹給大家呀...
有時我們會將一個集合資料以","分隔組合成一字串..例如:aaa,bbb,ccc
利用String.Join就可以做到了...省下很多程式碼的判斷....
asp.net(c#)
strJoin.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="strJoin.aspx.cs" Inherits="strJoin" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>strJoin</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:CheckBoxList ID="CheckBoxList1" runat="server"
- RepeatDirection="Horizontal">
- <asp:ListItem>F6 Team</asp:ListItem>
- <asp:ListItem>Puma</asp:ListItem>
- <asp:ListItem>Dotblogs</asp:ListItem>
- <asp:ListItem>tech‧ed 2008</asp:ListItem>
- </asp:CheckBoxList>
- <asp:TextBox ID="TextBox1" runat="server" Width="300px"></asp:TextBox>
- <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Join" />
- </div>
- </form>
- </body>
- </html>
strJoin.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Collections.Generic;
- public partial class strJoin : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- List<string> list = new List<string>();
- foreach (ListItem item in this.CheckBoxList1.Items)
- {
- if (item.Selected)
- {
- list.Add(item.Text);
- }
- }
- this.TextBox1.Text = string.Join(",",list.ToArray());
- }
- }
執行結果:
參考網址:
http://msdn.microsoft.com/zh-tw/library/57a79xd0(VS.80).aspx
转自:http://www.dotblogs.com.tw/puma/archive/2008/08/26/5200.aspx