using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication105.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Dictionary<string, string> DictionaryList = GetDictionary();
//根据字典Key获取Value
string name = DictionaryList["S001"];
//修改字典的Value
DictionaryList["S001"] = "学生01";
//foreach遍历字典
foreach (KeyValuePair<string, string> item in DictionaryList)
{
string key = item.Key;
string value = item.Value;
}
//for遍历字典
for (int i = 0; i < DictionaryList.Count; i++)
{
KeyValuePair<string, string> item = DictionaryList.ElementAt(i);
string key = item.Key;
string value = item.Value;
}
return View();
}
/// <summary>
/// 往字典中添加数据
/// </summary>
/// <returns></returns>
private Dictionary<string, string> GetDictionary()
{
Dictionary<string, string> DictionaryList = new Dictionary<string, string>();
DictionaryList.Add("S001", "学生1");
DictionaryList.Add("S002", "学生2");
DictionaryList.Add("S003", "学生3");
DictionaryList.Add("S004", "学生4");
DictionaryList.Add("S005", "学生5");
return DictionaryList;
}
}
}C# Dictionary使用
最新推荐文章于 2025-04-02 19:21:37 发布
本文介绍了一个使用C#进行字典操作的例子,包括如何创建、读取、更新字典中的数据,并提供了两种不同的遍历字典的方法。
4583

被折叠的 条评论
为什么被折叠?



