1.ArrayList 动态数组
using System;
using System.Collections;
namespace Day16_1
{
//动态数组
//特点:
//1.动态添加或减少元素
//2.实现了Icollection\IList\Ienumerable接口
//3.灵活的设置数组大小
//4.不安全的集合类型
//5。其元素为值类型时,效率不高(装箱拆箱耗性能)
public class LearnArrayList
{
public static void ArrayListDemo()
{
//实例化动态数组对象,默认是没有元素的
ArrayList numbers = new ArrayList();
//-----------------------------------------------------
//1.添加元素Add
numbers.Add(1);
numbers.Add(1);
numbers.Add(1);
numbers.Add(1.5f);
numbers.Add("3.14");
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[1]);
Console.WriteLine(numbers[2]);
//-----------------------------------------------------
//2.删除元素Remove
//通过一个值删除
numbers.Remove(1);//有多个相同的数,只删一个
numbers.Remove(123);//没有就删除不了,也不提示
//通过下标删除
numbers.RemoveAt(1);//删除下标为1的元素
//-----------------------------------------------------
//3.遍历素组
//for遍历动态数组元素
for (int i = 0; i < numbers.Count; i++)
{
Console.WriteLine(numbers[i]);
}
//foreach遍历动态数组元素
//必须实现了IEnumerator接口
foreach (object item in numbers)
{
Console.WriteLine(item);
}
//-----------------------------------------------------
//4.插入元素Insert
//在指定位置插入元素
numbers.Insert(1,10);//
foreach (object item in numbers)
{
Console.WriteLine(item);
}
//5.将数组元素逆转
numbers.Reverse();
//6.判断元素是否在动态数组中
bool test = numbers.Contains(1);//返回值为Bool类型
Console.WriteLine(test);
//7.清空动态数组
numbers.Clear();
//8.CopyTo
//9.IndeOf
//10.RemoveRange(int index,int count)
//11.Sort
}
}
class Program
{
//数组*****************************************************************
//局限性
//1,只能存储相同数据类型的数据
//2.长度是固定的,不能扩展
//优点
//数组开辟的内存是连续的,知道下标的话,读取容易
/**容器型数据类型**/
//集合*****************************************************************
//集合可以动态调整长度(变长)
//泛型集合:存相同的数据类型
//
//非泛型集合:存储的是万能基类object,几乎所有数据类型都可以存储,缺点是需要装箱拆箱
//动态数组(ArrayList),抽象类
//堆栈(Stack)
//队列(Queue)
//哈希表(HashTable)
static void Main(string[] args)
{
LearnArrayList.ArrayListDemo();
}
}
}
2.List<T> 泛型动态数组
using System;
using System.Collections.Generic;
namespace Day16_2
{
class Program
{
static void Main(string[] args)
{
//List<T>
//泛型动态数组
//List类是ArrayList类的泛型等效类
//同样实现了IList接口,IEnumrator接口和ICollection
//与ArrayList不同的是,声明集合时需要声明集合内部的数据类型,即T的类型
//安全的集合类型
//某种情况时,在处理值类型时其处理速度比ArrayList快的多
//泛型动态数组实例化
List<int> numbers = new List<int>();
//添加
numbers.Add(1);
numbers.Add(2);
numbers.Add((int)2.2f);
//删除
numbers.Remove(1);//删除第一个出现1的元素
numbers.RemoveAt(2);//删除索引处为2的元素
//插入
numbers.Insert(1,2);//插入索引处为1的地方
//反转
numbers.Reverse();//反转数组
//判断是否含有
numbers.Contains(1); //判断是否含有1
//清空
numbers.Clear();
//遍历
for (int i = 0; i < numbers.Count; i++)
{
Console.WriteLine(numbers[i]);
}
foreach (var item in numbers)
{
Console.WriteLine(numbers[item]);
}
}
}
}
3.Stack 堆栈(泛型、非泛型)
using System;
using System.Collections;
using System.Collections.Generic;
namespace Day16_3
{
//堆栈
//后进先出(LIFO)的一种数据结构,本质上堆栈也是一种线性结构
//线性结构的基本特点:即每个节点有且只有一个前驱结点和一个后续节点
//随着像Stack中添加元素,容量通过重新分配按需自动增加
//可以接受null作为有效值
//允许重复的元素
//不安全的数据结构
//其泛型为Stack<T>
class LearnStack
{
Stack numbers = new Stack();
}
class Tstack
{
Stack<float> littleNumbers = new Stack<float>();
}
class Program
{
//Stack堆栈
//常用方法
//Push()
//Pop()
//Peek()
//Contains()
//Clear()
//Count()
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
4.Queue 队列(泛型、非泛型)
using System;
using System.Collections.Generic;
namespace Day16_4
{
//队列Queue
//先进先出(FIFO)的一种数据结构
//随着像Queue中添加元素,容量通过重新分配按需自动增加,可以通过TrimToSize来减少容量
//可以接受null作为有效值
//允许重复的元素
//不安全的数据结构
//其泛型为Queue<T>
//在A*算法中会用优先级队列处理路径节点
class LearnQueue
{
public static void QueueDemo()
{
//队列实例化
Queue<string> words = new Queue<string>();
//进队列
words.Enqueue("xiaoming");
words.Enqueue("xiaohong");
//出队列
//获取队列队头元素,并移除
string person = words.Dequeue();
Console.WriteLine(person);
string person1 = words.Dequeue();
Console.WriteLine(person1);
string person2 = words.Peek();
Console.WriteLine(person2);
//Coutains()
//Clear()
//Count()
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
5.Dictionary 字典
using System;
using System.Collections.Generic;
using System.Linq;
namespace Day16_5
{
class Program
{
//字典(Dictionary)
//处理和表现类似key-value的键值对的集合
//Key和Value的类型由泛型指定
//key值必须唯一,区分大小写
//Value可以是值类型变量,也可以是对象
//两个元素,成对存在
//(key,value),key必须时唯一的
class Equip
{
}
class LearnDiationary
{
public static void DicDemo()
{
//实例化字典
Dictionary<string,Equip> equips = new Dictionary<string, Equip>();
Equip abc = new Equip();
//向字典中添加元素
equips.Add("a",new Equip());
equips.Add("ABC",abc);
//删除字典中的元素
equips.Remove("a");
//判断key是否存在
bool iscontains = equips.ContainsKey("a");
//判断value是否存在
bool contains1 = equips.ContainsValue(abc);
//获取字典中的元素
Equip equip = equips["a"];
//遍历只能用foreach
foreach (var item in equips)
{
Console.WriteLine(item);
}
//只遍历keys
foreach (var item in equips.Keys)
{
Console.WriteLine(item);
}
//只遍历values
foreach (var item in equips.Values)
{
//item是一个迭代变量,是不能被赋值的
Console.WriteLine(item);
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
6.HashTable 哈希表
using System;
namespace Day16_6
{
class Program
{
//HashTable哈希表
//处理和表现类似key-value的键值对的集合
//Key和Value都是object类型
//key值必须唯一,区分大小写
//Value可以是值类型变量,也可以是对象
//Add() 将指定的键和值添加到哈希表中
//Clear() 从 Hashtable中移除所有的元素。
//ContainsKey() 判断 Hashtable是否包含指定的键。
//ContainsValue() 判断 Hashtable是否包含指定的值。
//Remove() 从 Hashtable中移除带有指定的键的元素。
//Keys 获取一个ICollection,包含Hashtable中的键。
//Values 获取一个ICollection包含Hashtable中的值
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
老师做法:
using System;
using System.Collections.Generic;
namespace aHomework
{
class Student : IComparable<Student>
{
private string name;
private char sex;
private byte age;
private string id;
private string address;
/// <summary>
/// 分数
/// </summary>
private Dictionary<string,float> scores;
public Student(string id, string name)
{
this.id = id;
this.name = name;
scores = new Dictionary<string, float>();
}
public Student(string id,string name,
char sex,byte age,
string address) : this(id,name)
{
this.sex = sex;
this.age = age;
this.address = address;
}
/// <summary>
/// 自我介绍
/// </summary>
public void ShowMe()
{
Console.WriteLine("-------学生信息---------");
Console.WriteLine($"学号:{id}");
Console.WriteLine($"姓名:{name}");
if (sex != '\0')
{
Console.WriteLine($"性别:{sex}");
}
if (age != 0)
{
Console.WriteLine($"年龄:{age}");
}
if (!string.IsNullOrEmpty(address))
{
Console.WriteLine($"地址:{address}");
}
Console.WriteLine("----------------------");
}
public Dictionary<string, float> Scores
{
get => scores;
set => scores = value;
}
public string Address
{
get => address;
set => address = value;
}
public string Id
{
get => id;
set => id = value;
}
public byte Age
{
get => age;
set => age = value;
}
public char Sex
{
get => sex;
set => sex = value;
}
public string Name
{
get => name;
set => name = value;
}
private int CompareToByAge(Student other)
{
// 此对象 另一个对象
if (this.Age < other.Age)
{
return -1;
}
else if(this.Age > other.Age)
{
return 1;
}
else
{
return 0;
}
}
private int CompareToByScore(Student other)
{
//先比较没有成绩的情况
if (scores.Count == 0)
return 1;
if (other.scores.Count == 0)
return -1;
//遍历的顺序:第一遍【数学】第二遍【语文】第三遍【英语】
foreach (var item in scores)
{
//我的分数
if (item.Value > other.scores[item.Key])
{
return -1;
}
else if(item.Value < other.scores[item.Key])
{
return 1;
}
}
return 0;
}
public int CompareTo(Student other)
{
// return CompareToByAge(other);
return CompareToByScore(other);
}
}
public enum StudentMsgType
{
Name,
Age,
Sex
}
class StudentManager
{
#region Singleton
private static StudentManager instance;
public static StudentManager GetInstance()
{
if (instance == null)
{
instance = new StudentManager();
}
return instance;
}
private StudentManager()
{
studentDictionary = new Dictionary<string, Student>();
studentList = new List<Student>();
}
#endregion
private Dictionary<string, Student> studentDictionary;
private List<Student> studentList;
/// <summary>
/// 添加学生
/// </summary>
/// <param name="student"></param>
public void AddStudent(Student student)
{
if (student == null)
{
Console.WriteLine("学生不能为null...");
return;
}
if (string.IsNullOrEmpty(student.Id))
{
Console.WriteLine("传入的学生没有学号,禁止添加!");
return;
}
//判断学生列表中是否已经存在该学号
if (studentDictionary.ContainsKey(student.Id))
{
Console.WriteLine("学生列表中已经存在该学号,禁止添加!");
return;
}
//添加学生
studentDictionary.Add(student.Id, student);
Console.WriteLine($"添加学生{student.Name}成功!");
}
/// <summary>
/// 添加新生
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
public void AddStudent(string id, string name)
{
//实例化学生对象
Student stu = new Student(id, name);
AddStudent(stu);
}
/// <summary>
/// 根据学号移除学生
/// </summary>
/// <param name="studentID"></param>
public void RemoveStudent(string studentID)
{
if (studentDictionary.ContainsKey(studentID))
{
//移除学生
studentDictionary.Remove(studentID);
Console.WriteLine($"移除学号为{studentID}的学生成功!");
}
else
{
Console.WriteLine($"{studentID}所对应的学号,不存在...");
}
}
/// <summary>
/// 根据学生姓名查询
/// </summary>
/// <param name="studentName"></param>
/// <returns></returns>
public Student[] SeachStudent(StudentMsgType msgType, object studentMsg)
{
int count = 0;
//先创建List
List<Student> sameNameStudentsList = new List<Student>();
foreach (var item in studentDictionary.Values)
{
bool matchName = msgType == StudentMsgType.Name && item.Name == studentMsg.ToString();
bool matchSex = msgType == StudentMsgType.Sex && item.Sex == Convert.ToChar(studentMsg);
bool matchAge = msgType == StudentMsgType.Age && item.Age == Convert.ToByte(studentMsg);
if (matchName || matchSex || matchAge)
{
//展示学生信息
item.ShowMe();
count++;
//添加到列表
sameNameStudentsList.Add(item);
}
}
if (count == 0)
{
switch (msgType)
{
case StudentMsgType.Name:
Console.WriteLine($"不存在姓名为:{studentMsg}的学生");
break;
case StudentMsgType.Sex:
Console.WriteLine($"不存在性别为:{studentMsg}的学生");
break;
case StudentMsgType.Age:
Console.WriteLine($"不存在年龄为:{studentMsg}的学生");
break;
}
return null;
}
Student[] sameNameStudents = new Student[count];
//将List中的学生拷贝到数组中
sameNameStudentsList.CopyTo(sameNameStudents);
//返回结果
return sameNameStudents;
}
/// <summary>
/// 将字典中的数据导入List
/// </summary>
private void StudentsDicToList()
{
//清空List
studentList.Clear();
foreach (var item in studentDictionary.Values)
{
studentList.Add(item);
}
}
private void StudentsListToDic()
{
//清空List
studentDictionary.Clear();
foreach (var item in studentList)
{
studentDictionary.Add(item.Id,item);
}
}
/// <summary>
/// 学生根据年龄排序
/// </summary>
public void SortByAge()
{
//导入
StudentsDicToList();
//排序
studentList.Sort();
foreach (var item in studentList)
{
Console.WriteLine($"姓名:{item.Name} - 年龄:{item.Age}");
}
}
public void SortByScores()
{
//导入
StudentsDicToList();
//排序
studentList.Sort();
foreach (var item in studentList)
{
Console.WriteLine($"姓名:{item.Name}\t");
foreach (var scoreItem in item.Scores)
{
Console.WriteLine($"科目:{scoreItem.Key} - 成绩:{scoreItem.Value}");
}
}
}
}
internal class Program
{
public static void Main(string[] args)
{
StudentManager.GetInstance().AddStudent("200201","张三");
StudentManager.GetInstance().AddStudent("200202","李四");
Student student1 = new Student("200203","王五",'男',18,"北京");
student1.Scores.Add("math",80);
student1.Scores.Add("chinese",70);
student1.Scores.Add("english",60);
Student student2 = new Student("200204","赵六",'女',17,"北京");
student2.Scores.Add("math",100);
student2.Scores.Add("chinese",80);
student2.Scores.Add("english",80);
Student student3 = new Student("200205","冯七",'男',18,"北京");
student3.Scores.Add("math",80);
student3.Scores.Add("chinese",70);
student3.Scores.Add("english",20);
Student student4 = new Student("200206","赵六",'男',28,"北京");
student4.Scores.Add("math",100);
student4.Scores.Add("chinese",60);
student4.Scores.Add("english",60);
StudentManager.GetInstance().AddStudent(student1);
StudentManager.GetInstance().AddStudent(student2);
StudentManager.GetInstance().AddStudent(student3);
StudentManager.GetInstance().AddStudent(student4);
StudentManager.GetInstance().AddStudent(student4);
StudentManager.GetInstance().RemoveStudent("200202");
StudentManager.GetInstance().SeachStudent(StudentMsgType.Name, "赵六");
Console.WriteLine("**************");
StudentManager.GetInstance().SeachStudent(StudentMsgType.Age, 18);
Console.WriteLine("**************");
StudentManager.GetInstance().SeachStudent(StudentMsgType.Sex, '男');
Console.WriteLine("****************************");
// StudentManager.GetInstance().SortByAge();
StudentManager.GetInstance().SortByScores();
}
}
}
我的做法:
using System;
using System.Collections;
using System.Collections.Generic;
namespace test_1
{
class Student : IComparable<Student>
{
public string name;
public string sex;
public int age;
public string ID;
public string adress;
public int[] grade;
public Student(string name, string sex, int age, string id, string adress, int[] grade)
{
this.name = name;
this.sex = sex;
this.age = age;
ID = id;
this.adress = adress;
this.grade = grade;
}
/*
public int CompareTo(Student other)
{
if (this.age >= other.age)
{
return 1;//空值比较大,返回1
}
return this.age.CompareTo(other.age);//升序
//return other.age.CompareTo(this.age);//降序
}
*/
public int CompareTo(Student other)
{
if (this.grade[0] > other.grade[0])
{
return 1;//空值比较大,返回1
}
else if(this.grade[0]==other.grade[0])
{
if (this.grade[1] > other.grade[1])
{
return 1;
}
else if (this.grade[1] == other.grade[1])
{
if (this.grade[2]>other.grade[2])
{
return 1;
}
}
}
return this.age.CompareTo(other.age);//升序
//return other.age.CompareTo(this.age);//降序
}
/*
public int Compare(Student x, Student y)
{
if (x.age < y.age)
return -1;
else if (x.age == y.age)
return 0;
else
return 1;
}
*/
}
class MyList
{
List<Student> StudentMsg = new List<Student>();
//添加学生
public void AddStudent(Student student)
{
int flag = 0;
foreach (var item in StudentMsg)
{
flag++;
if (item.ID == student.ID)
{
Console.WriteLine("学生ID已存在,无法添加...");
}
}
if (flag == StudentMsg.Count)
{
StudentMsg.Add(student);
Console.WriteLine("该学生添加成功!");
}
}
//移除学生
public void RemoveStudent(string ID)
{
int flag = 0;
for (int i = 0; i < StudentMsg.Count; i++)
{
flag++;
if (StudentMsg[i].ID==ID)
{
StudentMsg.Remove(StudentMsg[i]);
Console.WriteLine($"学号为{ID}的学生删除成功!");
break;
}
}
if (flag == StudentMsg.Count)
{
Console.WriteLine($"系统没有学号为{ID}的学生,无法删除...");
}
}
//查询学生
public void SearchStudentByName(string name)
{
int flag = 0;
for (int i = 0; i < StudentMsg.Count; i++)
{
flag++;
if (StudentMsg[i].name==name)
{
Console.WriteLine($"姓名:{StudentMsg[i].name}," +
$"性别:{StudentMsg[i].sex}," +
$"年龄:{StudentMsg[i].age}," +
$"学号:{StudentMsg[i].ID}," +
$"地址:{StudentMsg[i].adress}," +
$"数学:{StudentMsg[i].grade[1]}," +
$"语文:{StudentMsg[i].grade[0]}," +
$"英语:{StudentMsg[i].grade[2]}");
}
}
if (flag == StudentMsg.Count)
{
Console.WriteLine($"系统中没有姓名为{name}的学生...");
}
}
public void SearchStudentBySex(string sex)
{
int flag = 0;
for (int i = 0; i < StudentMsg.Count; i++)
{
if (StudentMsg[i].sex==sex)
{
Console.WriteLine($"姓名:{StudentMsg[i].name}," +
$"性别:{StudentMsg[i].sex}," +
$"年龄:{StudentMsg[i].age}," +
$"学号:{StudentMsg[i].ID}," +
$"地址:{StudentMsg[i].adress}," +
$"数学:{StudentMsg[i].grade[1]}," +
$"语文:{StudentMsg[i].grade[0]}," +
$"英语:{StudentMsg[i].grade[2]}");
}
}
if (flag == StudentMsg.Count)
{
Console.WriteLine($"系统中没有性别为{sex}的学生...");
}
}
public void SearchStudentByAge(int age)
{
int flag = 0;
for (int i = 0; i < StudentMsg.Count; i++)
{
if (StudentMsg[i].age==age)
{
Console.WriteLine($"姓名:{StudentMsg[i].name}," +
$"性别:{StudentMsg[i].sex}," +
$"年龄:{StudentMsg[i].age}," +
$"学号:{StudentMsg[i].ID}," +
$"地址:{StudentMsg[i].adress}," +
$"数学:{StudentMsg[i].grade[1]}," +
$"语文:{StudentMsg[i].grade[0]}," +
$"英语:{StudentMsg[i].grade[2]}");
}
}
if (flag == StudentMsg.Count)
{
Console.WriteLine($"系统中没有年龄为{age}的学生...");
}
}
//排序
public void SortStudentByAge()
{
StudentMsg.Sort();
for (int i = 0; i < StudentMsg.Count; i++)
{
Console.WriteLine($"姓名:{StudentMsg[i].name}," +
$"性别:{StudentMsg[i].sex}," +
$"年龄:{StudentMsg[i].age}," +
$"学号:{StudentMsg[i].ID}," +
$"地址:{StudentMsg[i].adress}," +
$"数学:{StudentMsg[i].grade[1]}," +
$"语文:{StudentMsg[i].grade[0]}," +
$"英语:{StudentMsg[i].grade[2]}");
}
}
public void SortStudentByGrade()
{
StudentMsg.Sort();
for (int i = 0; i < StudentMsg.Count; i++)
{
Console.WriteLine($"姓名:{StudentMsg[i].name}," +
$"性别:{StudentMsg[i].sex}," +
$"年龄:{StudentMsg[i].age}," +
$"学号:{StudentMsg[i].ID}," +
$"地址:{StudentMsg[i].adress}," +
$"数学:{StudentMsg[i].grade[1]}," +
$"语文:{StudentMsg[i].grade[0]}," +
$"英语:{StudentMsg[i].grade[2]}");
}
}
}
class Program
{
static void Main(string[] args)
{
MyList test = new MyList();
int[] a = new[] {90, 90, 90};
Student s1 = new Student("小明","男",18,"180801","北京市昌平区",a);
int[] b = new[] {80, 100, 80};
Student s2 = new Student("小红","女",17,"180802","北京市顺义区",b);
int[] c = new[] {100, 80, 100};
Student s3 = new Student("小刚","男",19,"180703","北京市东城区",c);
test.AddStudent(s1);
test.AddStudent(s2);
test.AddStudent(s3);
Console.WriteLine("------------------------------------------------------------------");
//test.RemoveStudent("180801");
Console.WriteLine("------------------------------------------------------------------");
test.SearchStudentByAge(17);
Console.WriteLine("------------------------------------------------------------------");
test.SearchStudentByName("小明");
Console.WriteLine("------------------------------------------------------------------");
test.SearchStudentBySex("男");
Console.WriteLine("------------------------------------------------------------------");
test.SortStudentByAge();
Console.WriteLine("------------------------------------------------------------------");
test.SortStudentByGrade();
Console.WriteLine("------------------------------------------------------------------");
}
}
}