建立 100 个 int 的 array, int 为随机数字 介於 1 ~ 100
选出大於 50 的 复数数字 (%2 = 0), 使用 List<int> 储存
使用预设排序 List<int>
foreach 印出 List内的 int
随机数字生成范例: 使用System.Random
void test1()
{
List<int> list1 =newList<int>();//List[int]
for (int i = 0; i < 100; i++)
{
Random rd =newRandom(i);
int RandKey = rd.Next(1, 101);//产生100个随机数
Console.WriteLine(RandKey);
if (RandKey > 50 && RandKey % 2 == 0)
{
list1.Add(RandKey);
Console.WriteLine("-----------------");
}
}
foreach (int iin list1)//遍历
{
Console.Write(i +"--");
}
}
使用Dictionary(Key => Value 存取的泛型资料 Container)
挑选 IT 10个人, 以工号为 key, 姓名为 value, 建立一个 Dictionary 储存
将工号 K开头的人员姓名印出
字串判断含有 ‘K’ 的范例:
void test2()
{
Dictionary<String,String> list2 =newDictionary<string,string>();
list2.Add("K2580","AA");
list2.Add("M2584","BB");
list2.Add("A2544","CC");
list2.Add("K2588","DD");
list2.Add("S2536","EE");
list2.Add("K2467","FF");
list2.Add("B2970","GG");
list2.Add("K2130","HH");
list2.Add("M7940","II");
list2.Add("U3283","JJ");
foreach (String keyin list2.Keys)
{
if (key.Contains("K"))
{
Console.WriteLine("key={0},value={1}", key, list2[key]);
}
}
}
使用 Queue(先进先出 (FIFO) Container)
设计一个计时触发机制
使用 Queue<>储存触发时间, 触发时印出当前时间
间隔时间为随机秒数 0 ~ 10, 建议使用 System.DateTime 处理
共触发 5 次
例如:
当前时间 00秒 -> 隔3 秒触发 -> 隔7秒触发 -> etc...
void test3()
{
Queue<DateTime> queue =newQueue<DateTime>();
DateTime nowTime =DateTime.Now;//获取当前时间
Console.WriteLine("当前时间:" + nowTime);
DateTime nextTime = nowTime;//定义触发时间
for (int i = 0; i < 5; i++)//触发5次
{
Random rd =newRandom(i);
int RandKey = rd.Next(0, 11);
nextTime =nextTime.AddSeconds(RandKey);//每次间隔后的触发时间
Console.WriteLine("第{0}次触发时间为{1},间隔为{2}秒", i, nextTime, RandKey);
queue.Enqueue(nextTime);
}
while (queue.Count > 0)//触发判断
{
//Console.WriteLine(DateTime.Now);
if (DateTime.Now == queue.Peek())
{
Console.WriteLine(queue.Dequeue());
}
}
queue.Clear();
}
使用 Stack(後进先出 (LIFO) container)
建立一个 字串 Undo 机制, 建议使用 System.Text.StringBuilder 操作字串
使用 Stack 纪录 每一次 append 字串的内容,
透过 Stack pop 纪录执行 Undo Append 的功能
例如:
空字串 -> Append“a”-> Append“b”-> Append“c”-> Undo -> Undo
“” -> “a” -> “ab” -> “abc” -> “ab”-> “a”
void test4()
{
Stack<String> stack =newStack<string>();
String text ="";
Console.WriteLine("key in:");
A: for(int i = 0; i < 100; i++)
{
String newText =Console.ReadLine();
if (newText.Equals("undo"))
{
if (stack.Count == 0)
{
Console.WriteLine("结束");
return;
}
text = text.Remove(text.Length-stack.Peek().Length,stack.Peek().Length);
Console.WriteLine("NOWTEXT:{0}", text);
stack.Pop();
}
else
{
stack.Push(newText);
text = text + newText;
Console.WriteLine("NOWTEXT:{0}", text);
}
}