ASP.NET Tutorial/Collections/ArrayList
Содержание
- 1 Add objects to ArrayList (C#)
- 2 Add objects to ArrayList (VB)
- 3 ArrayList with custom objects
- 4 Using an ArrayList
- 4.1 Select customer from list:
- 4.2 Customer Information
- 4.3 Bind ArrayList to DropDownList
- 4.4 Foreach loop (C#)
- 4.5 Foreach loop (VB)
- 4.6 Using a custom strongly typed PersonList (C#)
- 4.7 Using a custom strongly typed PersonList (VB)
- 4.8 Using an ArrayList instead of an array (C#)
- 4.9 Using an ArrayList instead of an array (VB)
Add objects to ArrayList (C#)
<source lang="csharp">
<%@ Page Language="C#" %> <script runat="server"> private void Page_Load(object sender, System.EventArgs e) {
System.Collections.ArrayList al = new System.Collections.ArrayList(5); al.Add("one"); al.Add(2); al.Add(false); al.Add(new System.Object()); Response.Write("Successfully added " + al.Count + " different types of objects to an ArrayList.");
} </script></source>
Add objects to ArrayList (VB)
<source lang="csharp">
<%@ Page Language="VB" %> <script runat="server"> Sub Page_Load (Sender As Object, E As EventArgs)
Dim al As New ArrayList(5) al.Add("one") al.Add(2) al.Add(False) al.Add(New System.Object()) Response.Write("Successfully added " & al.Count & " different types of objects to an ArrayList.")
End Sub </script></source>
ArrayList with custom objects
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UsingArrayList" %> <!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 id="Head1" runat="server">
<title>Using an ArrayList</title>
</head> <body>
<form id="form1" runat="server">
Using an ArrayList
In this example, the drop-down list is
data bound to an ArrayList
.
<asp:Panel ID="panList" runat="server" >
Select customer from list:
<asp:ListBox id="lboxCustomers" runat="server" AutoPostBack="True" DataTextField="Name" DataValueField="Id" OnSelectedIndexChanged="SelectCustomer" /> </asp:Panel> <asp:Panel ID="panCustomer" runat="server" CssClass="panelBox">
Customer Information
Id:
<asp:TextBox id="txtId" runat="server" /> First Name:
<asp:TextBox id="txtFirst" runat="server" /> Last Name:
<asp:TextBox id="txtLast" runat="server" /> Phone Number:
<asp:TextBox id="txtPhone" runat="server" /> </asp:Panel>
</form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public abstract class AbstractEntity {
private string _id; public AbstractEntity(string id) { _id = id; }
public string Id { get { return _id; } set { _id = value; } }
public abstract bool IsValid { get; }
} public class Customer: AbstractEntity {
// data members private string _firstName; private string _lastName; private string _phone; public Customer(string id, string firstName, string lastName, string phone): base(id) { _firstName = firstName; _lastName = lastName; _phone = phone; }
public string FirstName { get { return _firstName; } set { _firstName = value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } public string Phone { get { return _phone; } set { _phone = value; } } public string Name { get { return LastName + ", " + FirstName; } } public override bool IsValid { get { if (Id.Length > 0 && LastName.Length > 0) return true; else return false; } } public override string ToString() { return Id + "," + Name + "," + Phone; }
} public partial class UsingArrayList : System.Web.UI.Page {
private ArrayList _customers; private void Page_Load(object sender, System.EventArgs e) { _customers = new ArrayList(); FillCustomers(); if (!IsPostBack) { lboxCustomers.DataSource = _customers; lboxCustomers.DataBind(); panCustomer.Visible = false; } } private void FillCustomers() { Customer c1 = new Customer("1", "A", "AA", "123-4567"); Customer c2 = new Customer("2", "B", "BB", "456-1267"); Customer c3 = new Customer("3", "C", "CC", "564-7823"); Customer c4 = new Customer("4", "D", "DD", "253-6383"); _customers.Add(c1); _customers.Add(c2); _customers.Add(c3); _customers.Add(c4); }
protected void SelectCustomer(object sender, System.EventArgs e) { int index = lboxCustomers.SelectedIndex; if (index >= 0 && index <= _customers.Count) { Customer c = (Customer)_customers[index]; txtId.Text = c.Id; txtFirst.Text = c.FirstName; txtLast.Text = c.LastName; txtPhone.Text = c.Phone; panCustomer.Visible = true; } }
}</source>
Bind ArrayList to DropDownList
<source lang="csharp">
<script language="C#" runat="server"> protected void Page_Load(object o, EventArgs e) {
if(!IsPostBack) { ArrayList arrayList = new ArrayList(); arrayList.Add("C#"); arrayList.Add("VB.NET"); arrayList.Add("JScript.Net"); languageDropDownList.DataSource = arrayList; languageDropDownList.DataBind(); favoriteLanguage.Text = languageDropDownList.SelectedItem.Value; }
} protected void DropDownListSelectionChanged(object o, EventArgs e) {
favoriteLanguage.Text = languageDropDownList.SelectedItem.Text;
} </script> <form runat="server"> <asp:DropDownList
id="languageDropDownList" runat="server" OnSelectedIndexChanged="DropDownListSelectionChanged" >
</asp:DropDownList>
Favorite Language: <asp:Label runat="server" id="favoriteLanguage" style="color:blue" />
<asp:Button runat="server" Text="Submit"/>
</form></source>
Foreach loop (C#)
<source lang="csharp">
<%@ Page %> <script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e) { int i; System.Collections.ArrayList myList=new System.Collections.ArrayList(); myList.Add("Zero"); myList.Add("One"); myList.Add("Two"); myList.Add("Three"); myList.Add("Four"); myList.Add("Five"); foreach (string number in myList) { Response.Write(number.ToString() + "
"); } }
</script> <html>
<body> <form id="form1" method="post" runat="server"> </form> </body>
</html></source>
Foreach loop (VB)
<source lang="csharp">
<%@ Page %> <script language="vb" runat="server">
Sub Page_Load(sender As Object, e As EventArgs) Dim i As Integer Dim item As String Dim myList As New System.Collections.ArrayList() myList.Add("Zero") myList.Add("One") myList.Add("Two") myList.Add("Three") myList.Add("Four") myList.Add("Five") For Each item In myList Response.Write(Item & "
") Next End Sub
</script> <html>
<body> <form id="form1" method="post" runat="server"> </form> </body>
</html></source>
Using a custom strongly typed PersonList (C#)
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
</form>
</body> </html> File: Default.aspx.cs using System; using System.Collections; public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { Person scott = new Person("A", "B"); Person bill = new Person("C", "D"); Person srini = new Person("E", "F"); PersonList people = new PersonList(); people.Add(scott); people.Add(bill); people.Add(srini); foreach (Person p in people) { Response.Write(p.FullName + "
"); } for (int i = 0; i < people.Count; i++) { Response.Write(people[i].FullName + "
"); } }
} public class PersonList : System.Collections.IEnumerable {
private ArrayList innerList = new ArrayList(); public void Add(Person aPerson) { innerList.Add(aPerson); } public void Remove(Person aPerson) { innerList.Remove(aPerson); } public int Count { get { return innerList.Count; } } // Get/set element at given index public Person this[int index] { get { return (Person)innerList[index]; } set { innerList[index] = value; } } public IEnumerator GetEnumerator() { return innerList.GetEnumerator(); }
}
public class Person : IComparable {
string FirstName; string LastName; public Person(string first, string last) { FirstName = first; LastName = last; } public string FullName { get { return FirstName + " " + LastName; } } int IComparable.rupareTo(object obj) { Person p2 = obj as Person; if (p2 == null) throw new ArgumentException("Object is not a Person!"); int lastNameResult = this.LastName.rupareTo(p2.LastName); if (lastNameResult == 0) { int firstNameResult = this.FirstName.rupareTo(p2.FirstName); return firstNameResult; } else { return lastNameResult; } }
}</source>
Using a custom strongly typed PersonList (VB)
<source lang="csharp">
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!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>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
</form>
</body> </html> File: Default.aspx.vb Imports System Imports System.Collections Imports Microsoft.VisualBasic Imports System.Collections Public Class PersonList
Implements System.Collections.IEnumerable Private innerList As ArrayList = New ArrayList() Public Sub Add(ByVal aPerson As Person) innerList.Add(aPerson) End Sub Public Sub Remove(ByVal aPerson As Person) innerList.Remove(aPerson) End Sub Public ReadOnly Property Count() As Integer Get Return innerList.Count End Get End Property "Get/set element at given index Default Public Property Item(ByVal index As Integer) As Person Get Return CType(innerList(index), Person) End Get Set(ByVal Value As Person) innerList(index) = Value End Set End Property Public Function GetEnumerator() As IEnumerator _ Implements IEnumerable.GetEnumerator Return innerList.GetEnumerator() End Function
End Class Public Class Person
Implements IComparable Dim FirstName As String Dim LastName As String Public Sub New(ByVal First As String, ByVal Last As String) FirstName = First LastName = Last End Sub Public ReadOnly Property FullName() As String Get Return FirstName & " " & LastName End Get End Property Public Function CompareTo(ByVal obj As Object) _ As Integer Implements IComparable.rupareTo If Not TypeOf (obj) Is Person Then Throw New ArgumentException("Object is not a Person!") End If Dim p2 As Person = CType(obj, Person) Dim lastNameResult As Integer = Me.LastName.rupareTo(p2.LastName) If lastNameResult = 0 Then Dim firstNameResult As Integer = Me.FirstName.rupareTo(p2.FirstName) Return firstNameResult Else Return lastNameResult End If End Function
End Class Partial Class _Default
Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load Dim scott As New Person("A", "B") Dim bill As New Person("C", "D") Dim srini As New Person("E", "F") Dim people As New PersonList() people.Add(scott) people.Add(bill) people.Add(srini) For Each p As Person In people Response.Write(p.FullName & "
") Next For i As Integer = 0 To people.Count - 1 Response.Write(people(i).FullName & "
") Next End Sub
End Class</source>
Using an ArrayList instead of an array (C#)
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
</form>
</body> </html> File: Default.aspx.cs using System; using System.Collections; public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { Person scott = new Person("A", "B"); Person bill = new Person("C", "D"); Person srini = new Person("E", "F"); ArrayList people = new ArrayList(); people.Add(scott); people.Add(bill); people.Add(srini); Response.Write("We used foreach.
"); foreach (Person p in people) { Response.Write(p.FullName + "
"); } Response.Write("Sort...
"); people.Sort(); Response.Write("We used foreach.
"); foreach (Person p in people) { Response.Write(p.FullName + "
"); } Person scott2 = new Person("A", "B"); int indexOfA2 = people.IndexOf(scott2); Response.Write("A #2 is at " + indexOfA2 + "
"); int indexOfEquivalentA = people.BinarySearch(scott2); Response.Write("An Equivalent A is at " + indexOfEquivalentA + "
"); Response.Write("We used a for loop.
"); for (int i = 0; i < people.Count; i++) { Response.Write(((Person)people[i]).FullName + "
"); } }
} public class Person : IComparable {
string FirstName; string LastName; public Person(string first, string last) { FirstName = first; LastName = last; } public string FullName { get { return FirstName + " " + LastName; } } int IComparable.rupareTo(object obj) { Person p2 = obj as Person; if (p2 == null) throw new ArgumentException("Object is not a Person!"); int lastNameResult = this.LastName.rupareTo(p2.LastName); if (lastNameResult == 0) { int firstNameResult = this.FirstName.rupareTo(p2.FirstName); return firstNameResult; } else { return lastNameResult; } }
}</source>
Using an ArrayList instead of an array (VB)
<source lang="csharp">
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!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>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
</form>
</body> </html> File: Default.aspx.vb Imports System Imports System.Collections Imports Microsoft.VisualBasic Public Class Person
Implements IComparable Dim FirstName As String Dim LastName As String Public Sub New(ByVal First As String, ByVal Last As String) FirstName = First LastName = Last End Sub Public ReadOnly Property FullName() As String Get Return FirstName & " " & LastName End Get End Property Public Function CompareTo(ByVal obj As Object) _ As Integer Implements IComparable.rupareTo If Not TypeOf (obj) Is Person Then Throw New ArgumentException("Object is not a Person!") End If Dim p2 As Person = CType(obj, Person) Dim lastNameResult As Integer = Me.LastName.rupareTo(p2.LastName) If lastNameResult = 0 Then Dim firstNameResult As Integer = Me.FirstName.rupareTo(p2.FirstName) Return firstNameResult Else Return lastNameResult End If End Function
End Class Partial Class _Default
Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load Dim scott As New Person("A", "B") Dim bill As New Person("C", "D") Dim srini As New Person("E", "F") Dim people As New ArrayList() people.Add(scott) people.Add(bill) people.Add(srini) Response.Write("Unsorted. We used foreach.
") For Each p As Person In people Response.Write(p.FullName & "
") Next Response.Write("Sort...
") people.Sort() Response.Write("Sorted. We used foreach.
") For Each p As Person In people Response.Write(p.FullName & "
") Next Dim scott2 As New Person("A", "B") Dim indexOfA2 As Integer = people.IndexOf(scott2) Response.Write("A #2 is at " & indexOfA2 & "
") Dim indexOfEquivalentA As Integer = people.BinarySearch(scott2) Response.Write("An Equivalent A is at " & _ indexOfEquivalentA & "
") Response.Write("We used a for loop.
") For i As Integer = 0 To people.Count - 1 Response.Write(CType(people(i), Person).FullName & "
") Next End Sub
End Class</source>