视频一区二区在线,精品成人一区二区三区免费视频,亚洲国产老妈http://www.aygfsteel.com/ebecket/category/40887.html一路風(fēng)景我一路走著,不管多么疲憊,因為一路的風(fēng)景很美....... zh-cnMon, 23 Nov 2009 02:27:52 GMTMon, 23 Nov 2009 02:27:52 GMT60 Conversion from Enum to String http://www.aygfsteel.com/ebecket/articles/303083.htmlbecket_zhengbecket_zhengFri, 20 Nov 2009 09:53:00 GMThttp://www.aygfsteel.com/ebecket/articles/303083.htmlhttp://www.aygfsteel.com/ebecket/comments/303083.htmlhttp://www.aygfsteel.com/ebecket/articles/303083.html#Feedback0http://www.aygfsteel.com/ebecket/comments/commentRss/303083.htmlhttp://www.aygfsteel.com/ebecket/services/trackbacks/303083.htmlI have an enum SortFilter, which looks like following:

publicenum SortFilter

{

      FirstName,

      LastName,

      Age,

      Experience

}

Now, let's say I want to display the string value of enum in some control. For that, I will have to convert Enum value to string. For example, I want to add all enum string values to a DropDownList. The following code loops through the enumeration and adds string values to it. Here SortByList is DropDownList.

SortByList.Items.Clear();

// Conversion from Enum to String

foreach (string item in Enum.GetNames(typeof(ArrayListBinding.SortFilter)))

{

      SortByList.Items.Add(item);
}    

This code converts an enum to string:

string name= Enum.GetName(typeof(ArrayListBinding.SortFilter), SortFilter.FirstName);

Now let's say, you have an enum string value say, "FirstName" and now you want to convert it to Enum value. The following code converts from a string to enum value, where Developer.SortingBy is of type SortFilter enumeration:

// Conversion from String to Enum

Developer.SortingBy = (SortFilter)Enum.Parse(typeof(SortFilter), "FirstName");  



becket_zheng 2009-11-20 17:53 發(fā)表評論
]]>
DateTime.Parse 與DateTime.ParseExacthttp://www.aygfsteel.com/ebecket/articles/303073.htmlbecket_zhengbecket_zhengFri, 20 Nov 2009 09:00:00 GMThttp://www.aygfsteel.com/ebecket/articles/303073.htmlhttp://www.aygfsteel.com/ebecket/comments/303073.htmlhttp://www.aygfsteel.com/ebecket/articles/303073.html#Feedback0http://www.aygfsteel.com/ebecket/comments/commentRss/303073.htmlhttp://www.aygfsteel.com/ebecket/services/trackbacks/303073.htmlC# Use DateTime.ParseExact() instead of DateTime.Parse()

I didn’t notice this until today, the DateTime I retrieve from my database has the format of yyyy/MM/dd hh:mm:ss.fff

and if I use DateTime.Parse(), the .fff value will be lost.

After searching google, I find out that not only DateTime.Parse() has this one problem, it also has problem with culture setting.

So, whenever you what to parse a DateTime, use DateTime.ParseExact().

Here is an useful example :

string[] DateTimeList = {
"yyyy/M/d tt hh:mm:ss",
"yyyy/MM/dd tt hh:mm:ss",
"yyyy/MM/dd HH:mm:ss",
"yyyy/M/d HH:mm:ss",
"yyyy/M/d",
"yyyy/MM/dd"
}; 
DateTime dt = DateTime.ParseExact(" 2008/  3/18   PM 02: 50:23  ",
DateTimeList,CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces
);

Remember, CultureInfo is important to parsing, for example tt in Chinese will be 上午/下午, in en-US will be AM/PM. You can use CultureInfo.CreateSpecificCulture() to create the culture you need.
A small pattern reference

yyyy year ‘2009′
MM month ‘04′
dd day ‘17′
HH 24 hour ‘23′
hh 12 hour ‘11′
mm minutes ‘59′
ss seconds ‘30′
tt AM/PM
zzz GMT


becket_zheng 2009-11-20 17:00 發(fā)表評論
]]>
C#代碼與javaScript函數(shù)的相互調(diào)用http://www.aygfsteel.com/ebecket/articles/302230.htmlbecket_zhengbecket_zhengFri, 13 Nov 2009 07:18:00 GMThttp://www.aygfsteel.com/ebecket/articles/302230.htmlhttp://www.aygfsteel.com/ebecket/comments/302230.htmlhttp://www.aygfsteel.com/ebecket/articles/302230.html#Feedback0http://www.aygfsteel.com/ebecket/comments/commentRss/302230.htmlhttp://www.aygfsteel.com/ebecket/services/trackbacks/302230.htmlC#代碼與javaScript函數(shù)的相互調(diào)用
2009年09月29日 星期二 14:32

出處:http://dotnet.csdn.net/page/c6e71327-58f8-4300-a87d-476c6ac80c4e

        http://hi.baidu.com/chaobaojun/blog/item/f307146f314d05d380cb4a03.html

C#代碼與javaScript函數(shù)的相互調(diào)用

問:
1.如何在JavaScript訪問C#函數(shù)?
2.如何在JavaScript訪問C#變量?
3.如何在C#中訪問JavaScript的已有變量?
4.如何在C#中訪問JavaScript函數(shù)?

問題1答案如下:
javaScript函數(shù)中執(zhí)行C#代碼中的函數(shù):
方法一:1、首先建立一個按鈕,在后臺將調(diào)用或處理的內(nèi)容寫入button_click中;
2、在前臺寫一個js函數(shù),內(nèi)容為document.getElementById("btn1").click();
3、在前臺或后臺調(diào)用js函數(shù),激發(fā)click事件,等于訪問后臺c#函數(shù);

方法二:1、函數(shù)聲明為public
后臺代碼(把public改成protected也可以)
public string ss()
{
return("a");
}
2、在html里用<%=fucntion()%>可以調(diào)用
前臺腳本
<script language=javascript>
var a = "<%=ss()%>";
alert(a);
</script>
方法三:1、<script language="javascript">
<!--
function __doPostBack(eventTarget, eventArgument)
{
var theForm = document.Form1; //指runat=server的form
theForm.__EVENTTARGET.value = eventTarget;
theFrom.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
-->
</script>
<input id="Button1" type="button" name="Button1" value="按鈕" onclick="javascript:__doPostBack('Button1','')">

方法四:<script language="javascript">
function SubmitKeyClick()
{
if (event.keyCode == 13)
{
event.cancelBubble = true;
event.returnValue = false;
document.all.FunName.value="你要調(diào)用的函數(shù)名";
document.form[0].submit();
}
}
</script>

<INPUT onkeypress="SubmitKeyClick()" id="aaa" type="text">
<input type="hidden" name="FunName"> 〈!--用來存儲你要調(diào)用的函數(shù) --〉

在.CS里有:
public Page_OnLoad()
{
if (!Page.IsPost())
{
string strFunName=Request.Form["FunName"]!=null?Request.Form["FunName"]:"";
//根據(jù)傳回來的值決定調(diào)用哪個函數(shù)
switch(strFunName)
{
case "enter()":
enter() ; //調(diào)用該函數(shù)
break;
case "其他":
//調(diào)用其他函數(shù)
break;
default:
//調(diào)用默認(rèn)函數(shù)
break;
}
}
}

public void enter()
{
//……比如計算某值
}

問題2.如何在JavaScript訪問C#變量?
答案如下:
方法一:1、通過頁面上隱藏域訪問<input id="xx" type="hidden" runat="server">
方法二:1、如后臺定義了PUBLIC STRING N; 前臺js中引用該變量的格式為'<%=n%>'或"+<%=n%>+"
方法三:1、或者你可以在服務(wù)器端變量賦值后在頁面注冊一段腳本
"<script language='javascript'>var temp=" + tmp + "</script>"
tmp是后臺變量,然后js中可以直接訪問temp獲得值。


3.如何在C#中訪問JavaScript的已有變量?

答案如下:

方法一:1、前臺使用靜態(tài)文本控件隱藏域,將js變量值寫入其中;
2、后臺用request["id"]來獲取值;舉例:把變量給一個隱藏控件 如lable textbox等document.getElementById("textbox的id").value=js變量值 然后后臺取 textbox.text

例:加一個textbox    id=text1
   js變量為 var i="測試";
js 里document.getElementById("text1").value=i;
后臺取 就用text1.text;

方法二:可以用cookie或session;
4.如何在C#中訪問JavaScript函數(shù)?
答案如下:
c#代碼中執(zhí)行javaScript函數(shù):
方法一:1、Page.RegisterStartupScript("ggg","<script>SetVisible(1); </script>");
方法二:使用Literal類,然后
private void Button2_Click(object sender, System.EventArgs e)
{
string str;
str="<script language='javascript'>";
str+="selectRange()";
str+="</script>";
//Literal1.Visible=true;
Literal1.Text=str;
}

文章出處:DIY部落(http://www.diybl.com/course/1_web/javascript/jsjs/200798/71020.html)

今天試著研究了一下服務(wù)器控件來控制JS代碼(可見不僅僅HTML控件可以調(diào)用JS方法,服務(wù)器控件也可以調(diào)用JS方法),

  本人覺得有點實用,現(xiàn)分享如下:

  前臺代碼如下:

js方法:<script language="javascript">
function check()
{
  if(document.all("CheckBox1").checked==true)
  {
    alert("OK");
   //document.getElementById('TextBox1').style.visibility="hidden";
   document.all('TextBox1').style.display="none"; //兩種方法均可控制TextBox的顯示與隱藏。
  }
  else
  {
   //document.getElementById('TextBox1').style.visibility="visible";
   document.all('TextBox1').style.display="block"; //兩種方法均可控制TextBox的顯示與隱藏。
  }
}
</script>

  一個TextBox和一個CheckBox。效果通過點擊CheckBox來控制TextBox的顯示與隱藏。

<body>
  <form id="form1" runat="server">
  <div>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:CheckBox ID="CheckBox1" runat="server" />
  </div>
  </form>
</body>

  在后臺頁面來調(diào)用JS方法,如下:

protected void Page_Load(object sender, EventArgs e)
  {
    CheckBox1.Attributes.Add("onclick","check()");
  }

  一般常用的客戶端調(diào)用的方法如下:

  JS方法不變,只是修改控件為HTML控件即可:

<body>
  <form id="form1" runat="server">
  <div>
    &nbsp;<input id="TextBox1" type="text" />
    <input id="Checkbox1" type="checkbox" onclick="check()" />
  
  </div>
  </form>
</body>

  另外還有兩種方法,

  (1).直接在服務(wù)器控件后面加上onclick事件,后臺不寫代碼。也行,如下:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:CheckBox ID="CheckBox1" runat="server" onclick="check()" />

  (2).在工具箱中拖兩個HTML控件,然后鼠標(biāo)右鍵,選“作為服務(wù)器控件運行”如下:

   <input id="TextBox1" type="text" runat="server" />
  <input id="Checkbox1" type="checkbox" runat="server" />

  然后再在后臺頁面來調(diào)用JS方法,如下:

protected void Page_Load(object sender, EventArgs e)
  {
    CheckBox1.Attributes.Add("onclick","check()");
  }



becket_zheng 2009-11-13 15:18 發(fā)表評論
]]>
去掉末尾的換行符http://www.aygfsteel.com/ebecket/articles/301994.htmlbecket_zhengbecket_zhengWed, 11 Nov 2009 10:19:00 GMThttp://www.aygfsteel.com/ebecket/articles/301994.htmlhttp://www.aygfsteel.com/ebecket/comments/301994.htmlhttp://www.aygfsteel.com/ebecket/articles/301994.html#Feedback0http://www.aygfsteel.com/ebecket/comments/commentRss/301994.htmlhttp://www.aygfsteel.com/ebecket/services/trackbacks/301994.html  textStr = textStr.TrimEnd((char[])"\n\r".ToCharArray()); 

becket_zheng 2009-11-11 18:19 發(fā)表評論
]]>
Google國際網(wǎng)站遭到域名劫持http://www.aygfsteel.com/ebecket/articles/301927.htmlbecket_zhengbecket_zhengWed, 11 Nov 2009 01:52:00 GMThttp://www.aygfsteel.com/ebecket/articles/301927.htmlhttp://www.aygfsteel.com/ebecket/comments/301927.htmlhttp://www.aygfsteel.com/ebecket/articles/301927.html#Feedback0http://www.aygfsteel.com/ebecket/comments/commentRss/301927.htmlhttp://www.aygfsteel.com/ebecket/services/trackbacks/301927.html  根據(jù)我的分析,這次封鎖Google的方式并不新鮮,是采用域名劫持(DNS劫持)的方法,通過技術(shù)手段,將Google的各類境外域名解析到一個錯誤的地址,使得Google.com無法訪問。前段時間,中央電視臺曾經(jīng)在多個欄目中指責(zé)Google,并要求其關(guān)閉境外網(wǎng)站搜索功能。

  經(jīng)過我的測試,使用中國大陸境內(nèi)的DNS服務(wù)器,例如202.96.134.133是無法正確解析出Google的IP地址,而使用境外的OpenDNS進(jìn)行域名解析,就可以正確解析出Google的IP地址。如下圖所示。

Google域名遭到域名劫持

  解決的方法是使用境外的域名解析服務(wù)器(DNS服務(wù)器),例如OpenDNS的服務(wù),設(shè)置方法是,在“設(shè)置”-“網(wǎng)絡(luò)連接”中找到寬帶上網(wǎng)的連接,打開網(wǎng)絡(luò)連接屬性,選擇Interner協(xié)議(TCP/IP)的屬性頁里,不要選擇自動獲取DNS,而要選擇“使用下面的DNS服務(wù)器地址”,首選DNS服務(wù)器和備用DNS服務(wù)器分別設(shè)置為208.67.222.222和208.67.220.220,如下圖所示,完成后重新連接上網(wǎng),就可以擺脫服務(wù)商對我們的DNS劫持。

網(wǎng)絡(luò)連接屬性

網(wǎng)絡(luò)連接屬性

  對于Google的域名劫持,這已經(jīng)不是第一次了,2002年的時候Google的域名就曾經(jīng)被劫持到百度等網(wǎng)站,2006年的時候Google.cn被域名劫持到萬網(wǎng)的買賣網(wǎng),這次輪到Google.com了,無論是誰在幕后操縱了這次域名劫持,都會給中國互聯(lián)網(wǎng)產(chǎn)生極為負(fù)面的影響,好在全球13臺DNS根服務(wù)器全都放在一些法制健全的國家(例如美國、日本),因此這次針對Google的域名劫持對于國外用戶沒有影響。

  最后,我強烈譴責(zé)這種對于Google網(wǎng)站進(jìn)行域名劫持的無恥行為。

  名詞解釋(來源于維基百科):

  DNS是域名系統(tǒng) (Domain Name Server) 的縮寫,該系統(tǒng)用于命名組織到域?qū)哟谓Y(jié)構(gòu)中的計算機和網(wǎng)絡(luò)服務(wù)。在Internet上域名與IP地址之間是一對一(或者一對多)的,域名雖然便于人們記憶,但機器之間只能互相認(rèn)識IP地址,它們之間的轉(zhuǎn)換工作稱為域名解析,域名解析需要由專門的域名解析服務(wù)器來完成,DNS就是進(jìn)行域名解析的服務(wù)器。

  域名解析的基本原理是把域名翻譯成IP地址,以便計算機能夠進(jìn)一步通信,傳遞網(wǎng)址和內(nèi)容等。

  域名劫持就是在劫持的網(wǎng)絡(luò)范圍內(nèi)攔截域名解析的請求,分析請求的域名,把審查范圍以外的請求放行,否則直接返回假的IP地址或者什么也不做使得請求失去響應(yīng),其效果就是對特定的網(wǎng)址不能訪問或訪問的是假網(wǎng)址。



becket_zheng 2009-11-11 09:52 發(fā)表評論
]]>
基于REST架構(gòu)的Web Service設(shè)計http://www.aygfsteel.com/ebecket/articles/301925.htmlbecket_zhengbecket_zhengWed, 11 Nov 2009 01:48:00 GMThttp://www.aygfsteel.com/ebecket/articles/301925.htmlhttp://www.aygfsteel.com/ebecket/comments/301925.htmlhttp://www.aygfsteel.com/ebecket/articles/301925.html#Feedback0http://www.aygfsteel.com/ebecket/comments/commentRss/301925.htmlhttp://www.aygfsteel.com/ebecket/services/trackbacks/301925.htmlApache Axis實現(xiàn)基于SOAP的Web Service實現(xiàn)技術(shù)和相關(guān)代碼,總的來說,SOAP的Web Service解決方案雖然較為成熟,且安全性較好,但是使用門檻較高,在大并發(fā)情況下會有性能問題,在互聯(lián)網(wǎng)上使用不太普及,因此并不太適合Web 2.0網(wǎng)站服務(wù)使用,目前大量的Web 2.0網(wǎng)站使用另外一種解決方案——REST。

  REST的架構(gòu)設(shè)計

  REST(Representational State Transfer)是一種輕量級的Web Service架構(gòu)風(fēng)格,其實現(xiàn)和操作明顯比SOAP和XML-RPC更為簡潔,可以完全通過HTTP協(xié)議實現(xiàn),還可以利用緩存Cache來提高響應(yīng)速度,性能、效率和易用性上都優(yōu)于SOAP協(xié)議。

  REST架構(gòu)遵循了CRUD原則,CRUD原則對于資源只需要四種行為:Create(創(chuàng)建)、Read(讀取)、Update(更新)和Delete(刪除)就可以完成對其操作和處理。這四個操作是一種原子操作,即一種無法再分的操作,通過它們可以構(gòu)造復(fù)雜的操作過程,正如數(shù)學(xué)上四則運算是數(shù)字的最基本的運算一樣。

  REST架構(gòu)讓人們真正理解我們的網(wǎng)絡(luò)協(xié)議HTTP本來面貌,對資源的操作包括獲取、創(chuàng)建、修改和刪除資源的操作正好對應(yīng)HTTP協(xié)議提供的GET、POST、PUT和DELETE方法,因此REST把HTTP對一個URL資源的操作限制在GET、POST、PUT和DELETE這四個之內(nèi)。這種針對網(wǎng)絡(luò)應(yīng)用的設(shè)計和開發(fā)方式,可以降低開發(fā)的復(fù)雜性,提高系統(tǒng)的可伸縮性。

  REST的設(shè)計準(zhǔn)則

  REST架構(gòu)是針對Web應(yīng)用而設(shè)計的,其目的是為了降低開發(fā)的復(fù)雜性,提高系統(tǒng)的可伸縮性。REST提出了如下設(shè)計準(zhǔn)則:

  網(wǎng)絡(luò)上的所有事物都被抽象為資源(resource);

  每個資源對應(yīng)一個唯一的資源標(biāo)識符(resource identifier);

  通過通用的連接器接口(generic connector interface)對資源進(jìn)行操作;

  對資源的各種操作不會改變資源標(biāo)識符;

  所有的操作都是無狀態(tài)的(stateless)。

  使用REST架構(gòu)

  對于開發(fā)人員來說,關(guān)心的是如何使用REST架構(gòu),這里我們來簡單談?wù)勥@個問題。REST不僅僅是一種嶄新的架構(gòu),它帶來的更是一種全新的Web開發(fā)過程中的思維方式:通過URL來設(shè)計系統(tǒng)結(jié)構(gòu)。REST是一套簡單的設(shè)計原則、一種架構(gòu)風(fēng)格(或模式),不是一種具體的標(biāo)準(zhǔn)或架構(gòu)。REST有很多成功的使用案例,著名的Delicious和Flickr都提供基于REST風(fēng)格的API使用,客戶端調(diào)用也極其方便,下面是我用ASP寫的一個很簡單的REST舉例,從中可以看出REST是多么的簡單易用。

  客戶端代碼:

Private Function httpGet(url, method, data)
    Dim xmlhttp
    Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
    xmlhttp.open method, url + "?" + data, False
    xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
    xmlhttp.setRequestHeader "Content-Length", Len(data)
    xmlhttp.send (Null)
    If (xmlhttp.Status = 200) Then httpGet = xmlhttp.responseText
    Set xmlhttp = Nothing
End Function

Private Function httpPost(url, method, data)
    Dim xmlhttp
    Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
    xmlhttp.open method, url, False
    xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
    xmlhttp.setRequestHeader "Content-Length", Len(data)
    xmlhttp.send (data)
    If (xmlhttp.Status = 200) Then httpPost = xmlhttp.responseText
    Set xmlhttp = Nothing
End Function

Private Function httpPut(url, method, data)
    Dim xmlhttp
    Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
    xmlhttp.open method, url, False
    xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
    xmlhttp.setRequestHeader "Content-Length", Len(data)
    xmlhttp.send (data)
    If xmlhttp.Status >= 400 And xmlhttp.Status <= 599 Then
        response.write " Error Occurred : " & xmlhttp.Status & " - " & xmlhttp.statusText
    Else
        response.write xmlhttp.responseText
    End If
    If (xmlhttp.Status = 200) Then httpPut = xmlhttp.responseText
    Set xmlhttp = Nothing
End Function

Private Function httpDelete(url, method, data)
    Dim xmlhttp
    Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
    xmlhttp.open method, url + "?" + data, False
    xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
    xmlhttp.setRequestHeader "Content-Length", Len(data)
    xmlhttp.send (Null)
    If xmlhttp.Status >= 400 And xmlhttp.Status <= 599 Then
        response.write " Error Occurred : " & xmlhttp.Status & " - " & xmlhttp.statusText
    Else
        response.write xmlhttp.responseText
    End If
    If (xmlhttp.Status = 200) Then httpDelete = xmlhttp.responseText
    Set xmlhttp = Nothing
End Function

response.write httpPost("http://localhost/rest/service.asp", "POST", "do=POST")
response.write httpGet("http://localhost/rest/service.asp", "GET", "do=GET")
response.write httpPut("http://localhost/rest/service.asp", "PUT", "do=PUT")
response.write httpDelete("http://localhost/rest/service.asp", "DELETE", "do=DELETE")

  服務(wù)端代碼:

Response.Write Request.ServerVariables("REQUEST_METHOD")
If (Request.ServerVariables("REQUEST_METHOD")="GET") Then
 Response.Write "DO GET" + Request("do")
ElseIf (Request.ServerVariables("REQUEST_METHOD")="POST") Then
 Response.Write "DO POST" + Request("do")
ElseIf (Request.ServerVariables("REQUEST_METHOD")="PUT") Then
 Response.Write "DO PUT" + Request("do")
ElseIf (Request.ServerVariables("REQUEST_METHOD")="DELETE") Then
 Response.Write "DO DELETE" + Request("do")
End if

  需要注意的是,IIS服務(wù)器默認(rèn)是不支持ASP文件的PUT和DELETE操作,默認(rèn)會返回“403 - Forbidden”錯誤,因此需要修改IIS的設(shè)置,修改方法是:管理根據(jù)-IIS信息服務(wù)器-網(wǎng)站-屬性-主目錄-應(yīng)用程序配置-配置-映射,選擇ASP - 編輯 - 修改為全部動作。

  關(guān)于更多關(guān)于REST方面的知識,建議閱讀《RESTful Web Services》這本書。



becket_zheng 2009-11-11 09:48 發(fā)表評論
]]>
C# List 用法http://www.aygfsteel.com/ebecket/articles/301842.htmlbecket_zhengbecket_zhengTue, 10 Nov 2009 07:46:00 GMThttp://www.aygfsteel.com/ebecket/articles/301842.htmlhttp://www.aygfsteel.com/ebecket/comments/301842.htmlhttp://www.aygfsteel.com/ebecket/articles/301842.html#Feedback0http://www.aygfsteel.com/ebecket/comments/commentRss/301842.htmlhttp://www.aygfsteel.com/ebecket/services/trackbacks/301842.html

C# List Examples

by Sam Allen - Updated September 6, 2009

Problem. You have questions about the List collection in the .NET Framework, which is located in the System.Collections.Generic namespace. You want to see examples of using List and also explore some of the many useful methods it provides, making it an ideal type for dynamically adding data. Solution. This document has lots of tips and resources on the List constructed type, with examples using the C# programming language.

--- Key points: ---                                           
    Lists are dynamic arrays in the C# language.              
    They can grow as needed when you add elements.            
    They are called generic collections and constructed types.
    You need to use < and > in the List declaration.          

1. Adding values

Here we see how to declare a new List of int values and add integers to it. This example shows how you can create a new List of unspecified size, and add four prime numbers to it. Importantly, the angle brackets are part of the declaration type, not conditional operators that mean less or more than. They are treated differently in the language.

~~~ Program that adds elements to List (C#) ~~~
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(5);
list.Add(7);
}
}

Adding objects. The above example shows how you can add a primitive type such as integer to a List collection, but the List collection can receive reference types and object instances. There is more information on adding objects with the Add method on this site. [C# List Add Method - dotnetperls.com]

2. Loops

Here we see how you can loop through your List with for and foreach loops. This is a very common operation when using List. The syntax is the same as that for an array, except your use Count, not Length for the upper bound. You can also loop backwards through your List by reversing the for loop iteration variables. Start with list.Count - 1, and proceed decrementing to >= 0.

~~~ Program that loops through List (C#) ~~~
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(7);
foreach (int prime in list) // Loop through List with foreach
{
Console.WriteLine(prime);
}
for (int i = 0; i < list.Count; i++) // Loop through List with for
{
Console.WriteLine(list[i]);
}
}
}
~~~ Output of the program ~~~
(Repeated twice)
2
3
7

3. Counting elements

To get the number of elements in your List, access the Count property. This is fast to access, if you avoid the Count() extension method. Count is equal to Length on arrays. See the section "Clearing List" for an example on using the Count property.

4. Clearing List—setting to null

Here we see how to use the Clear method, along with the Count property, to erase all the elements in your List. Before Clear is called, this List has 3 elements; after Clear is called, it has 0 elements. Alternatively, you can assign the List to null instead of calling Clear, with similar performance. However, after assigning to null, you must call the constructor again.

=== Program that counts List (C#) ===
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<bool> list = new List<bool>();
list.Add(true);
list.Add(false);
list.Add(true);
Console.WriteLine(list.Count); // 3
list.Clear();
Console.WriteLine(list.Count); // 0
}
}
=== Output of the program ===
3
0

5. Copying array to List

Here we see an easy way to create a new List with the elements in an array that already exists. You can use the List constructor and pass it the array as the parameter. List receives this parameter, and fills its values from it.

--- Program that copies array to List (C#) ---
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] arr = new int[3]; // New array with 3 elements
arr[0] = 2;
arr[1] = 3;
arr[2] = 5;
List<int> list = new List<int>(arr); // Copy to List
Console.WriteLine(list.Count);       // 3 elements in List
}
}
--- Output of the program ---
Indicates number of elements.
3

Notes on the example. It is useful to use the List constructor code here to create a new List from Dictionary keys. This will give you a List of the Dictionary keys. The array element type must match the type of the List elements, or the compiler will refuse to compile your code.

6. Finding elements

Here we an example of how you can test each element in your List for a certain value. This shows the foreach loop, which tests to see if 3 is in the List of prime numbers. Note that more advanced List methods are available to find matches in the List, but they often aren't any better than this loop. They can sometimes result in shorter code. [C# List Find Methods for Searching List - dotnetperls.com]

~~~ Program that uses foreach on List (C#) ~~~
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// New list for example
List<int> primes = new List<int>(new int[] { 2, 3, 5 });
// See if List contains 3
foreach (int number in primes)
{
if (number == 3) // Will match once
{
Console.WriteLine("Contains 3");
}
}
}
}
~~~ Output of the program ~~~
Contains 3

7. Using capacity

You can use the Capacity property on List, or pass an integer into the constructor, to improve allocation performance when using List. The author's research shows that capacity can improve performance by nearly 2x for adding elements. Note however that this is not usually a performance bottleneck in programs that access data. [C# Capacity Property - dotnetperls.com]

TrimExcess method. There is the TrimExcess method on List as well, but its usage is very limited and I have never needed to use it. It reduces the memory used. Note: "The TrimExcess method does nothing if the list is at more than 90 percent of capacity". [List(T).TrimExcess Method - MSDN]

8. Using BinarySearch

You can use the binary search algorithm on List with the instance BinarySearch method. Binary search uses guesses to find the correct element much faster than linear searching. It is often much slower than Dictionary. [C# BinarySearch List - dotnetperls.com]

9. Using AddRange and InsertRange

You can use AddRange and InsertRange to add or insert collections of elements into your existing List. This can make your code simpler. See an example of these methods on this site. [C# List AddRange Use - dotnetperls.com]

10. Using ForEach method

Sometimes you may not want to write a regular foreach loop, which makes ForEach useful. This accepts an Action, which is a void delegate method. Be very cautious when you use Predicates and Actions, because they can decrease the readability of your code.

Another useful method. There is a TrueForAll method that accepts a Predicate. If the Predicate returns true for each element in your List, the TrueForAll method will return true also. Else, it will return false.

11. Using Join—string List

Here we see how you can use string.Join on a List of strings. This is useful when you need to turn several strings into one comma-delimited string. It requires the ToArray instance method on List. The biggest advantage of Join here is that no trailing comma is present on the resulting string, which would be present in a loop where each string is appended.

=== Program that joins List (C#) ===
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// List of cities we need to join
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
// Join strings into one CSV line
string line = string.Join(",", cities.ToArray());
Console.WriteLine(line);
}
}
=== Output of the program ===
New York,Mumbai,Berlin,Istanbul

12. Getting List from Keys in Dictionary

Here we see how you can use the List constructor to get a List of keys in your Dictionary collection. This gives you a simple way to iterate over Dictionary keys, or store them elsewhere. The Keys instance property accessor on Dictionary returns an enumerable collection of keys, which can be passed to the List constructor as a parameter.

::: Program that converts Keys (C#) :::
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Populate example Dictionary
var dict = new Dictionary<int, bool>();
dict.Add(3, true);
dict.Add(5, false);
// Get a List of all the Keys
List<int> keys = new List<int>(dict.Keys);
foreach (int key in keys)
{
Console.WriteLine(key);
}
}
}
::: Output of the program :::
3, 5

13. Inserting elements

Here we see how you can insert an element into your List at any position. The string "dalmation" is inserted into index 1, which makes it become the second element in the List. Note that if you have to Insert elements extensively, you should consider the Queue and LinkedList collections for better performance. Additionally, a Queue may provide clearer usage of the collection in your code.

~~~ Program that inserts into List (C#) ~~~
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> dogs = new List<string>(); // Example List
dogs.Add("spaniel");         // Contains: spaniel
dogs.Add("beagle");          // Contains: spaniel, beagle
dogs.Insert(1, "dalmation"); // Contains: spaniel, dalmation, beagle
foreach (string dog in dogs) // Display for verification
{
Console.WriteLine(dog);
}
}
}
~~~ Output of the program ~~~
spaniel
dalmation
beagle

14. Removing elements

The removal methods on List are covered in depth in another article on this site. It contains examples for Remove, RemoveAt, RemoveAll, and RemoveRange, along with the author's notes. [C# List Remove Methods - dotnetperls.com]

15. Sorting and reversing

You can use the powerful Sort and Reverse methods in your List collection. These allow you to order your List in ascending or descending order. Additionally, you can use Reverse even when your List is not presorted. There is more information on these topics, as well as sorting your List with LINQ on a property on this site. [C# Sort List Method, Sorting and Reversing Lists - dotnetperls.com]

16. Converting List to array

You can convert your List to an array of the same type using the instance method ToArray. There are examples of this conversion, and the opposite, on this site. [C# Convert List to Array - dotnetperls.com]

17. Getting range of elements

Here we see how you can get a range of elements in your List collection using the GetRange instance method. This is similar to the Take and Skip methods from LINQ, but has different syntax.

--- Program that gets ranges from List (C#) ---
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> rivers = new List<string>(new string[]
{
"nile",
"amazon",     // River 2
"yangtze",    // River 3
"mississippi",
"yellow"
});
// Get rivers 2 through 3
List<string> range = rivers.GetRange(1, 2);
foreach (string river in range)
{
Console.WriteLine(river);
}
}
}
--- Output of the program ---
amazon
yangtze

18. Testing Lists for equality

Sometimes you may need to test two Lists for equality, even when their elements are unordered. You can do this by sorting both of them and then comparing, or by using a custom List equality method. This site contains an example of a method that tests lists for equality in an unordered way. [C# List Element Equality - dotnetperls.com]

19. Using List with structs

When using List, you can improve performance and reduce memory usage with structs instead of classes. A List of structs is allocated in contiguous memory, unlike a List of classes. This is an advanced optimization. Note that in many cases using structs will actually decrease the performance when they are used as parameters in methods such as those on the List type.

20. Using var keyword

Here we see how you can use List collections with the var keyword. This can greatly shorten your lines of code, which sometimes improves readability. The var keyword has no effect on performance, only readability for programmers.

~~~ Program that uses var with List (C#) ~~~
using System.Collections.Generic;
class Program
{
static void Main()
{
var list1 = new List<int>();       // <- var keyword used
List<int> list2 = new List<int>(); // <- Is equivalent to
}
}

21. Summary

Here we saw lots of examples with the List constructed type. You will find that List is powerful and performs well. It provides flexible allocation and growth, making it much easier to use than arrays. In most programs that do not have memory or performance constraints and must add elements dynamically, the List constructed type in the C# programming language is ideal.



List 類是 ArrayList 類的泛型等效類,某些情況下,用它比用數(shù)組和 ArrayList 都方便。

我們假設(shè)有一組數(shù)據(jù),其中每一項數(shù)據(jù)都是一個結(jié)構(gòu)。

public struct Item
{
    public int Id;
    public string DisplayText;
}

注意結(jié)構(gòu)是不能給實例字段賦值的,即 public int Id = 1 是錯誤的。

using System.Collections.Generic;

List<Item> items = new List<Item>();

//添加
Item item1 = new Item();
item1.Id = 0;
item1.DisplayText = "水星";
items.Add(item1);

//添加
Item item2 = new Item();
item2.Id = 1;
item2.DisplayText = "地球";
items.Add(item2);

//修改
//這里使用的是結(jié)構(gòu),故不能直接用 items[1].DisplayText = "金星";,如果 Item 是類,則可以直接用。為什么呢?因為結(jié)構(gòu)是按值傳遞的。
Item item = items[1];
item.DisplayText = "金星";
items[1] = item;







becket_zheng 2009-11-10 15:46 發(fā)表評論
]]>
NHibernate學(xué)習(xí)http://www.aygfsteel.com/ebecket/articles/287093.htmlbecket_zhengbecket_zhengFri, 17 Jul 2009 02:16:00 GMThttp://www.aygfsteel.com/ebecket/articles/287093.htmlhttp://www.aygfsteel.com/ebecket/comments/287093.htmlhttp://www.aygfsteel.com/ebecket/articles/287093.html#Feedback0http://www.aygfsteel.com/ebecket/comments/commentRss/287093.htmlhttp://www.aygfsteel.com/ebecket/services/trackbacks/287093.html閱讀全文

becket_zheng 2009-07-17 10:16 發(fā)表評論
]]>
主站蜘蛛池模板: 莱西市| 崇阳县| 方正县| 莱州市| 金塔县| 武陟县| 汕尾市| 泰来县| 安阳县| 积石山| 黑龙江省| 措美县| 阜康市| 漳浦县| 嘉禾县| 蒲江县| 丹江口市| 临沧市| 汕尾市| 富宁县| 聂荣县| 聊城市| 中方县| 大丰市| 大同市| 赫章县| 许昌市| 云林县| 彭阳县| 麻江县| 津南区| 定安县| 台南县| 和林格尔县| 德阳市| 贡嘎县| 读书| 克什克腾旗| 桂东县| 聂荣县| 灵台县|