集合类List与Dictonary实例练习

2019-05-20 12:58:45王振洲

student.Add( "小月月" , xyy);
student.Add( "凤姐" , fj);
student.Add( "芙蓉姐姐" , fr);
student.Add( "犀利哥" , xl);
Console .WriteLine(student["犀利哥" ].Name); //根据key获取value
//遍历 通过key
foreach (string item in student.Keys) {
Console .WriteLine(item);
Console .WriteLine(student[item].Age);
}
//遍历 通过value
foreach (Student item in student.Values) {
Console .WriteLine(item.Age);
}
//遍历键值对
foreach (KeyValuePair < string, Student > item in student) {
Console .WriteLine(item.Key);
Console .WriteLine(item.Value.Age);//item.Value是Student对象 直接使用
}
//移除
//student.Remove("小月月");
//student.Clear();
student.ContainsKey( "小月月" ); //是否包含该key
//更多参见帮助文档
Console .Read();
}
}
}

c、泛型集合练习

View Code
using System;
using System.Collections.Generic;
namespace _04__泛型练习 {
class Program {
static void Main( string[] args) {
//把分拣奇偶数的程序用泛型实现
string str = "7 4 3 2 9 8 33 22" ;
string [] strs = str.Split(' ' );
strs = Getevent(strs).ToArray();
string res = string .Join( " ", strs); //string数组 直接用join就好了
Console .WriteLine(res);
//将int数组中的奇数放到一个新的int数组中返回
int [] intarr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List <int > list = new List <int >();
foreach (int item in intarr) {
if (item % 2 != 0) {
list.Add(item);
}
}
intarr = list.ToArray();
foreach (int item in intarr) {
Console .WriteLine(item);
}
//从一个整数的List<int>中取出最大数。不使用自身带的Max()方法。
List <int > list2 = new List <int > { 1, 2, 3, 4, 5, 6, 7, 8 };
int max = list2[0];
foreach (int item in list2) {
if (item > max) {
max = item;
}
}
Console .WriteLine("泛型集合最大值为{0}" , max);
Console .ReadKey();
}
public static List< string > Getevent(string [] str) {
List <string > list = new List <string >();
List <string > list2 = new List <string >();
foreach (string item in str) {
if (int .Parse(item) % 2 != 0) {
list.Add(item);
} else {
list2.Add(item);
}
}
list.AddRange(list2);
return list;
}
}
}

d、泛型集合练习2

View Code
using System;
using System.Collections.Generic;
namespace _06_泛型集合练习 {
class Program {
static void Main( string[] args) {
//把1,2,3转换为壹贰叁
string str = "1壹 2贰 3叁 4肆 5伍 6陆 7柒 8捌 9玖 0零" ;
Dictionary <char , char> money = new Dictionary < char, char >();
string [] strs = str.Split(' ' );
string s = "123456789" ;
string news = "" ;
for (int i = 0; i < strs.Length; i++) {
money.Add(strs[i][0], strs[i][1]);