using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DictionaryWithClassExample
{
    // 自定义学生类
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Major { get; set; }
        public double GPA { get; set; }

        // 构造函数
        public Student(int id, string name, int age, string major, double gpa)
        {
            Id = id;
            Name = name;
            Age = age;
            Major = major;
            GPA = gpa;
        }

        // 重写ToString方法以便在列表框中显示
        public override string ToString()
        {
            return $"ID: {Id} | 姓名: {Name} | 年龄: {Age} | 专业: {Major} | GPA: {GPA:F2}";
        }
    }

    public partial class MainForm : Form
    {
        // 创建字典存储学生信息,键为学生ID,值为Student对象
        private Dictionary<int, Student> students = new Dictionary<int, Student>();
        
        public MainForm()
        {
            InitializeComponent();
            InitializeUI();
            AddSampleData(); // 添加一些示例数据
        }

        private void InitializeUI()
        {
            // 设置窗体属性
            this.Text = "学生信息管理系统 - C#字典与类的应用";
            this.Size = new Size(700, 500);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 创建控件
            var lblId = new Label { Text = "学生ID:", Location = new Point(20, 20), Size = new Size(60, 20) };
            var txtId = new TextBox { Location = new Point(90, 20), Size = new Size(100, 20), Tag = "id" };
            
            var lblName = new Label { Text = "姓名:", Location = new Point(200, 20), Size = new Size(60, 20) };
            var txtName = new TextBox { Location = new Point(260, 20), Size = new Size(100, 20), Tag = "name" };
            
            var lblAge = new Label { Text = "年龄:", Location = new Point(370, 20), Size = new Size(60, 20) };
            var txtAge = new TextBox { Location = new Point(430, 20), Size = new Size(60, 20), Tag = "age" };
            
            var lblMajor = new Label { Text = "专业:", Location = new Point(20, 50), Size = new Size(60, 20) };
            var txtMajor = new TextBox { Location = new Point(90, 50), Size = new Size(150, 20), Tag = "major" };
            
            var lblGPA = new Label { Text = "GPA:", Location = new Point(250, 50), Size = new Size(60, 20) };
            var txtGPA = new TextBox { Location = new Point(310, 50), Size = new Size(60, 20), Tag = "gpa" };
            
            var btnAdd = new Button { Text = "添加/更新", Location = new Point(380, 45), Size = new Size(90, 30) };
            var btnRemove = new Button { Text = "删除", Location = new Point(480, 45), Size = new Size(80, 30) };
            var btnClear = new Button { Text = "清空", Location = new Point(570, 45), Size = new Size(80, 30) };
            
            var lstStudents = new ListBox { Location = new Point(20, 90), Size = new Size(650, 250) };
            
            var lblStats = new Label { Text = "统计信息:", Location = new Point(20, 350), Size = new Size(650, 40) };
            
            var lblSearch = new Label { Text = "搜索:", Location = new Point(20, 400), Size = new Size(60, 20) };
            var txtSearch = new TextBox { Location = new Point(80, 400), Size = new Size(150, 20) };
            var btnSearch = new Button { Text = "按专业搜索", Location = new Point(240, 395), Size = new Size(100, 30) };
            var btnSortByGPA = new Button { Text = "按GPA排序", Location = new Point(350, 395), Size = new Size(100, 30) };
            var btnSortByName = new Button { Text = "按姓名排序", Location = new Point(460, 395), Size = new Size(100, 30) };

            // 添加控件到窗体
            this.Controls.AddRange(new Control[] {
                lblId, txtId, lblName, txtName, lblAge, txtAge, lblMajor, txtMajor, lblGPA, txtGPA,
                btnAdd, btnRemove, btnClear, lstStudents, lblStats,
                lblSearch, txtSearch, btnSearch, btnSortByGPA, btnSortByName
            });

            // 添加按钮事件处理
            btnAdd.Click += (s, e) => {
                if (ValidateInputs(new[] { txtId, txtName, txtAge, txtMajor, txtGPA }, out int id, out string name, out int age, out string major, out double gpa))
                {
                    // 创建Student对象并添加到字典
                    Student student = new Student(id, name, age, major, gpa);
                    students[id] = student; // 添加或更新
                    UpdateListBox(lstStudents);
                    UpdateStats(lblStats);
                    ClearInputs(new[] { txtId, txtName, txtAge, txtMajor, txtGPA });
                }
            };

            btnRemove.Click += (s, e) => {
                if (int.TryParse(txtId.Text, out int id))
                {
                    // 从字典中移除指定键
                    if (students.Remove(id))
                    {
                        UpdateListBox(lstStudents);
                        UpdateStats(lblStats);
                        ClearInputs(new[] { txtId, txtName, txtAge, txtMajor, txtGPA });
                    }
                    else
                    {
                        MessageBox.Show("未找到该学生ID!");
                    }
                }
                else
                {
                    MessageBox.Show("请输入有效的学生ID!");
                }
            };

            btnClear.Click += (s, e) => {
                // 清空字典
                students.Clear();
                UpdateListBox(lstStudents);
                UpdateStats(lblStats);
            };

            btnSearch.Click += (s, e) => {
                string major = txtSearch.Text.Trim();
                if (!string.IsNullOrEmpty(major))
                {
                    // 使用LINQ查询特定专业的学生
                    var filteredStudents = students.Values.Where(s => s.Major.Contains(major)).ToList();
                    lstStudents.Items.Clear();
                    foreach (var student in filteredStudents)
                    {
                        lstStudents.Items.Add(student);
                    }
                }
            };

            btnSortByGPA.Click += (s, e) => {
                // 使用LINQ按GPA降序排序
                var sortedStudents = students.Values.OrderByDescending(s => s.GPA).ToList();
                lstStudents.Items.Clear();
                foreach (var student in sortedStudents)
                {
                    lstStudents.Items.Add(student);
                }
            };

            btnSortByName.Click += (s, e) => {
                // 使用LINQ按姓名升序排序
                var sortedStudents = students.Values.OrderBy(s => s.Name).ToList();
                lstStudents.Items.Clear();
                foreach (var student in sortedStudents)
                {
                    lstStudents.Items.Add(student);
                }
            };

            // 列表选择事件
            lstStudents.SelectedIndexChanged += (s, e) => {
                if (lstStudents.SelectedItem is Student selectedStudent)
                {
                    // 将选中的学生信息显示在输入框中
                    txtId.Text = selectedStudent.Id.ToString();
                    txtName.Text = selectedStudent.Name;
                    txtAge.Text = selectedStudent.Age.ToString();
                    txtMajor.Text = selectedStudent.Major;
                    txtGPA.Text = selectedStudent.GPA.ToString("F2");
                }
            };

            // 初始更新
            UpdateListBox(lstStudents);
            UpdateStats(lblStats);
        }

        // 添加一些示例数据
        private void AddSampleData()
        {
            students.Add(1001, new Student(1001, "张三", 20, "计算机科学", 3.8));
            students.Add(1002, new Student(1002, "李四", 21, "物理学", 3.5));
            students.Add(1003, new Student(1003, "王五", 22, "计算机科学", 3.9));
            students.Add(1004, new Student(1004, "赵六", 19, "数学", 3.2));
            students.Add(1005, new Student(1005, "钱七", 20, "电子工程", 3.6));
        }

        // 验证输入
        private bool ValidateInputs(TextBox[] textBoxes, out int id, out string name, out int age, out string major, out double gpa)
        {
            id = 0;
            name = "";
            age = 0;
            major = "";
            gpa = 0;

            if (!int.TryParse(textBoxes[0].Text, out id))
            {
                MessageBox.Show("请输入有效的学生ID!");
                return false;
            }

            name = textBoxes[1].Text.Trim();
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("请输入姓名!");
                return false;
            }

            if (!int.TryParse(textBoxes[2].Text, out age) || age < 0 || age > 150)
            {
                MessageBox.Show("请输入有效的年龄!");
                return false;
            }

            major = textBoxes[3].Text.Trim();
            if (string.IsNullOrEmpty(major))
            {
                MessageBox.Show("请输入专业!");
                return false;
            }

            if (!double.TryParse(textBoxes[4].Text, out gpa) || gpa < 0 || gpa > 4.0)
            {
                MessageBox.Show("请输入有效的GPA (0.0-4.0)!");
                return false;
            }

            return true;
        }

        // 清空输入框
        private void ClearInputs(TextBox[] textBoxes)
        {
            foreach (var textBox in textBoxes)
            {
                textBox.Clear();
            }
        }

        // 更新列表框显示字典内容
        private void UpdateListBox(ListBox listBox)
        {
            listBox.Items.Clear();
            foreach (var student in students.Values)
            {
                listBox.Items.Add(student);
            }
        }

        // 更新统计信息
        private void UpdateStats(Label label)
        {
            if (students.Count == 0)
            {
                label.Text = "统计信息: 暂无数据";
                return;
            }

            // 使用LINQ计算统计信息
            int total = students.Count;
            double avgGPA = students.Values.Average(s => s.GPA);
            double maxGPA = students.Values.Max(s => s.GPA);
            double minGPA = students.Values.Min(s => s.GPA);
            double avgAge = students.Values.Average(s => s.Age);

            // 按专业分组统计
            var majorGroups = students.Values
                .GroupBy(s => s.Major)
                .Select(g => new { Major = g.Key, Count = g.Count() })
                .OrderByDescending(g => g.Count);

            string majorStats = string.Join(", ", majorGroups.Select(g => $"{g.Major}: {g.Count}"));

            label.Text = $"统计信息: 总人数: {total} | 平均GPA: {avgGPA:F2} | 最高GPA: {maxGPA:F2} | 最低GPA: {minGPA:F2} | 平均年龄: {avgAge:F1} | 专业分布: {majorStats}";
        }
    }

    internal static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}

更多推荐