List泛型集合

1 List泛型集合的使用

1.1 List<T>简要介绍

对于集合:定义的时候,无需规定元素的个数。
泛型:表示一种程序特性,也就是我们在定义的时候,无需指定特定的类型,而在使用的时候,我们必须明确类型。可以应用在集合中、方法中、类中。表示为<T>。<T>表示泛型,T是Type的简写,表示当前不确定具体类型。可以根据用户的实际需要,确定当前集合需要存放的数据类型,一旦确定不可改变。
要求:添加到集合中的元素类型,必须和泛型集合定义时规定的数据类型完全一致。数据取出后无需强制转换。

使用前的准备:

  • 引入命名空间:System.Collections.Generic。
  • 确定存储类型:List students = new List();

1.2 List<T>的创建

  1. 使用add方法依次添加。
List<Course> courseList = new List<Course>();
courseList.Add(course1);
courseList.Add(course2);
courseList.Add(course3);
courseList.Add(course4);
courseList.Add(course5);
  1. 使用集合初始化器,将元素一次性的初始化到集合中。
List<Course> courseList = new List<Course>() { course1, course2, course3, course4, course5 };
// Course[] courseArray1 = new Course[] { course1, course2, course3, course4, course5 };
  1. 把数组中的元素添加到集合中。
List<Course> courseListFromArray = new List<Course>();
courseListFromArray.AddRange(courseArray1);

1.3 List<T>和Array的互相转换

//集合转换到数组
Course[] courseArray2 = courseList.ToArray();
//数组直接转换到集合
List<Course> courseList3 = courseArray2.ToList();

1.4 List<T>删除元素

courseList.Remove(course3);//必须要掌握
courseList.RemoveAll(c => c.CourseId > 10002);//了解
courseList.RemoveAt(2);
courseList.RemoveRange(1, 2);

1.5 List<T>的遍历

  1. 使用for循环。
for (int i = 0; i < courseList.Count; i++)
{
    Console.WriteLine($"{item.CourseId}\t{item.CourseName}\t{item.ClassHour}\t{item.Teacher}");
}
  1. 使用foreach。
foreach (Course item in courseList)
{
    Console.WriteLine($"{item.CourseId}\t{item.CourseName}\t{item.ClassHour}\t{item.Teacher}");
}

1.6 List<T>的快速查询

集合查询方法1:

List<Course> result1 = courseList.FindAll(c => c.CourseId > 10003);

集合查询方法2:

var result2 = from c in courseList where c.CourseId > 10003 select c;
var result3 = result2.ToList();

2 List泛型集合的排序

2.1 值类型元素的排序

List<int> ageList = new List<int> { 20, 19, 25, 30, 26 };
ageList.Sort();//默认按照升序排列

foreach (int item in ageList)
{
    Console.WriteLine(item);
}
ageList.Reverse();	//降序

foreach (int item in ageList)
{
    Console.WriteLine(item);
}

2.2 类类型元素使用默认比较器进行排序

我们对需要排序的类实现系统接口IComparable<Course>。

public class Course : IComparable<Course>
{
    public Course() { }
    public Course(int courseId, string courseName, int classHour, string teacher)
    {
        this.CourseId = courseId;
        this.CourseName = courseName;
        this.ClassHour = classHour;
        this.Teacher = teacher;
    }
    public int CourseId { get; set; }//课程编号
    public string CourseName { get; set; }//课程名称
    public int ClassHour { get; set; }//课时
    public string Teacher { get; set; }//主讲老师

    //接口对应的比较方法(这个方法的签名,千万不要动)
    public int CompareTo(Course other)
    {
        //return this.CourseId.CompareTo(other.CourseId);
        return other.CourseId.CompareTo(CourseId);
        //如果把this放到前面,表示按照升序排列,other放到前面就是按照降序排列
    }
}

2.3 类类型元素使用比较器接口进行排序

以上我们使用默认比较器进行排序,很不方便,如果我们需要多种排序,怎么办?比较器接口:其实就是我们可以任意的指定对象属性排序,从而实现动态排序。

/// <summary>
/// 课程编号升序
/// </summary>
class CourseIdASC : IComparer<Course>
{
    public int Compare(Course x, Course y)
    {
        return x.CourseId.CompareTo(y.CourseId);
    }
}

// 使用方式
//排序方法的定义: public void Sort(IComparer<T> comparer);
courseList.Sort(new CourseIdASC());

2.4 其他高级排序方法

// 使用LINQ实现排序
var list1 = from c in courseList orderby c.CourseId ascending select c;
// 使用扩展方法OrderByDescending实现降序
var list2 = courseList.OrderByDescending(c => c.CourseId);
// 使用扩展方法OrderBy实现升序
var list3 = courseList.OrderBy(c => c.ClassHour);

3 泛型集合List作为DataGridView数据源展示和动态排序实现

3.1 项目文件和界面UI

项目文件如下:
在这里插入图片描述
界面UI:
在这里插入图片描述
对于界面中的DataGridView需要注意,启用添加、启用编辑、启用删除、启用列重新排序全部不要勾选。
在这里插入图片描述

3.2 代码实现

FrmMain.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ListOrder_20191217
{
    public partial class FrmMain : Form
    {
        List<Student> list = null;
        public FrmMain()
        {
            InitializeComponent();
            InitList();
        }

        private void InitList()
        {
            Student student1 = new Student() { Name = "Lili", Age = 20, Id = "1000", Addr = "广东省广州市" };
            Student student2 = new Student() { Name = "Mary", Age = 22, Id = "1004", Addr = "北京市" };
            Student student3 = new Student() { Name = "Yang", Age = 25, Id = "1001", Addr = "湖南省长沙市" };
            Student student4 = new Student() { Name = "LangLang", Age = 23, Id = "1003", Addr = "湖北省武汉市" };
            Student student5 = new Student() { Name = "Chi", Age = 28, Id = "1002", Addr = "广西省桂林市" };

            list = new List<Student>() { student1, student2, student3, student4, student5 };
        }

        private void btnShowStuInfo_Click(object sender, EventArgs e)
        {
            dgvStuInfo.DataSource = list;
            //dgvStuInfo.AutoResizeColumns();
        }

        private void btnASCOrderById_Click(object sender, EventArgs e)
        {
            dgvStuInfo.DataSource = list;
            list.Sort(new IdASC());
            dgvStuInfo.Refresh();
        }

        private void btnDESCOrderById_Click(object sender, EventArgs e)
        {
            dgvStuInfo.DataSource = list;
            list.Sort(new IdDESC());
            dgvStuInfo.Refresh();
        }
    }
}

Student.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ListOrder_20191217
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Id { get; set; }
        public string Addr { get; set; }
    }

    /// <summary>
    /// 学号升序排列
    /// </summary>
    public class IdASC : IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
            return x.Id.CompareTo(y.Id);
        }
    }

    /// <summary>
    /// 学号降序排列
    /// </summary>
    public class IdDESC : IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
            return y.Id.CompareTo(x.Id);
        }
    }
}


参考资料:

  1. .NET/C#工控上位机VIP系统学习班【喜科堂互联教育】
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#集合List是一种可以存储任意类的动态数组,它位于System.Collections.Generic命名空间下。语法如下:List<T> listName = new List<T>(); 其中T代表参数,可以是任意有效的C#数据类。(引用) List集合可以通过add方法逐个添加元素,也可以使用AddRange方法将另一个List集合添加到当前集合中。例如,可以创建两个List<int>对象,一个用于存储偶数,一个用于存储奇数,然后将奇数集合添加到偶数集合中,并通过foreach循环遍历输出集合中的元素。代码如下(引用): ```csharp int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<int> listEven = new List<int>(); List<int> listOdd = new List<int>(); foreach (int num in nums) { if (num % 2 == 0) { listEven.Add(num); } else { listOdd.Add(num); } } listEven.AddRange(listOdd); foreach (int item in listEven) { Console.Write(item + " "); } Console.ReadKey(); ``` 使用集合List的一个好处是可以避免频繁的类转换。通过指定参数,我们可以直接在集合中存储特定类的对象,而无需进行繁琐的类转换。这样可以提高代码的可读性和效率。(引用)<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [C#中List用法,必知必会!](https://blog.csdn.net/qq_44034384/article/details/106312390)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [c#List集合](https://blog.csdn.net/linxianming_/article/details/125979400)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值