using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, int> dict = new Dictionary<string, int>();
DataTable dt = GetDataTable();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
if (!dict.ContainsKey(dr[0].ToString()))
dict.Add(dr[0].ToString(), Int32.Parse(dr[1].ToString()));
//而使用索引器来赋值时,如果键已经存在,就会修改已有的键的键值
// dict[dr[0].ToString()] = Int32.Parse(dr[1].ToString());
}
}
//泛型结构体
foreach (KeyValuePair<string, int> kvp in dict)
Response.Write("key=" + kvp.Key + ",value=" + kvp.Value + "<br />");
//输出结果:
// key=新闻,value=3
// key=产品,value=8
//===================================================//
Dictionary<int, Person> pdict = new Dictionary<int, Person>();
for (int i = 1; i < 3; i++)
{
Person p = new Person();
p.Id = i;
p.Name = "名称 " + i;
pdict.Add(i, p);
}
//获取值得集合
foreach (Person p in pdict.Values)
{
Response.Write("id=" + p.Id + ",name=" + p.Name + "<br />");
}
//输出结果:
// id=1,name=名称 1
// id=2,name=名称 2
}
DataTable GetDataTable()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("Type", typeof(string)));
dt.Columns.Add(new DataColumn("Amount", typeof(Int32)));
dr = dt.NewRow();
dr[0] = "新闻";
dr[1] = "3";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "产品";
dr[1] = "8";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "产品";
dr[1] = "8";
dt.Rows.Add(dr);
return dt;
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
/*
//C#3.0 Dictionary初始化赋值的新语法
Dictionary<int, string> dic = new Dictionary<int, string>{
{1,"A"}, {2,"B"}, {3,"C"}, {4,"D"},{5,"E"},
{6,"F"}, {7,"G"}, {8,"H"},{9,"I"},{10,"J"},
{11,"K"},{12,"L"},{13,"M"},{14,"N"},{15,"O"},
{16,"P"},{17,"Q"},{18,"R"},{19,"S"},{20,"T"},
{21,"U"}, {22,"V"},{23,"W"}, {24,"X"},{25,"Y"},
{26,"Z"}
};
*/
}