ASP.NET Tutorial/Collections/ArrayList
Содержание
- 1 Add objects to ArrayList (C#)
- 2 Add objects to ArrayList (VB)
- 3 ArrayList with custom objects
- 4 Bind ArrayList to DropDownList
- 5 Foreach loop (C#)
- 6 Foreach loop (VB)
- 7 Using a custom strongly typed PersonList (C#)
- 8 Using a custom strongly typed PersonList (VB)
- 9 Using an ArrayList instead of an array (C#)
- 10 Using an ArrayList instead of an array (VB)
Add objects to ArrayList (C#)
<%@ 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>
Add objects to ArrayList (VB)
<%@ 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>
ArrayList with custom objects
<%@ 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">
<div id="container">
<h1>Using an ArrayList</h1>
In this example, the drop-down list is
data bound to an <code>ArrayList</code>.
<asp:Panel ID="panList" runat="server" >
<h2>Select customer from list:</h2>
<asp:ListBox id="lboxCustomers" runat="server" AutoPostBack="True"
DataTextField="Name"
DataValueField="Id"
OnSelectedIndexChanged="SelectCustomer" />
</asp:Panel>
<asp:Panel ID="panCustomer" runat="server" CssClass="panelBox">
<h2>Customer Information</h2>
Id:<br />
<asp:TextBox id="txtId" runat="server" />
First Name:<br />
<asp:TextBox id="txtFirst" runat="server" />
Last Name:<br />
<asp:TextBox id="txtLast" runat="server" />
Phone Number:<br />
<asp:TextBox id="txtPhone" runat="server" />
</asp:Panel>
</div>
</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;
}
}
}
Bind ArrayList to DropDownList
<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><br/>
Favorite Language: <b><asp:Label runat="server" id="favoriteLanguage" style="color:blue" /></b><br />
<asp:Button runat="server" Text="Submit"/>
</form>
Foreach loop (C#)
<%@ 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() + "<BR>");
}
}
</script>
<html>
<body>
<form id="form1" method="post" runat="server">
</form>
</body>
</html>
Foreach loop (VB)
<%@ 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 & "<BR>")
Next
End Sub
</script>
<html>
<body>
<form id="form1" method="post" runat="server">
</form>
</body>
</html>
Using a custom strongly typed PersonList (C#)
<%@ 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">
<div>
</div>
</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 + "<BR/>");
}
for (int i = 0; i < people.Count; i++)
{
Response.Write(people[i].FullName + "<BR/>");
}
}
}
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;
}
}
}
Using a custom strongly typed PersonList (VB)
<%@ 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">
<div>
</div>
</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 & "<BR/>")
Next
For i As Integer = 0 To people.Count - 1
Response.Write(people(i).FullName & "<BR/>")
Next
End Sub
End Class
Using an ArrayList instead of an array (C#)
<%@ 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">
<div>
</div>
</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.<BR/>");
foreach (Person p in people)
{
Response.Write(p.FullName + "<BR/>");
}
Response.Write("Sort...<BR/>");
people.Sort();
Response.Write("We used foreach.<BR/>");
foreach (Person p in people)
{
Response.Write(p.FullName + "<BR/>");
}
Person scott2 = new Person("A", "B");
int indexOfA2 = people.IndexOf(scott2);
Response.Write("A #2 is at " + indexOfA2 + "<BR/>");
int indexOfEquivalentA = people.BinarySearch(scott2);
Response.Write("An Equivalent A is at " + indexOfEquivalentA +
"<BR/>");
Response.Write("We used a for loop.<BR/>");
for (int i = 0; i < people.Count; i++)
{
Response.Write(((Person)people[i]).FullName + "<BR/>");
}
}
}
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;
}
}
}
Using an ArrayList instead of an array (VB)
<%@ 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">
<div>
</div>
</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.<BR/>")
For Each p As Person In people
Response.Write(p.FullName & "<BR/>")
Next
Response.Write("Sort...<BR/>")
people.Sort()
Response.Write("Sorted. We used foreach.<BR/>")
For Each p As Person In people
Response.Write(p.FullName & "<BR/>")
Next
Dim scott2 As New Person("A", "B")
Dim indexOfA2 As Integer = people.IndexOf(scott2)
Response.Write("A #2 is at " & indexOfA2 & "<BR/>")
Dim indexOfEquivalentA As Integer = people.BinarySearch(scott2)
Response.Write("An Equivalent A is at " & _
indexOfEquivalentA & "<BR/>")
Response.Write("We used a for loop.<BR/>")
For i As Integer = 0 To people.Count - 1
Response.Write(CType(people(i), Person).FullName & "<BR/>")
Next
End Sub
End Class