• C# list泛型集合(线性表)


    一、#List泛型集合

      集合是OOP中的一个重要概念。

        为什么要用泛型集合?

        在C# 2.0之前,主要可以通过两种方式实现集合:

        1.使用ArrayList

        直接将对象放入ArrayList,操作直观,但由于集合中的项是Object类型,因此每次使用都必须进行繁琐的类型转换。

        2.使用自定义集合类

        比较常见的做法是从CollectionBase抽象类继承一个自定义类,通过对IList对象进行封装实现强类型集合。这种方式要求为每种集合类型写一个相应的自定义类,工作量较大。泛型集合的出现较好的解决了上述问题,只需一行代码便能创建指定类型的集合。

    List<>的括号和数组的[]括号是不一样的,List集合的括号<>是表示要输入的数据类型.

     怎样创建泛型集合?

        主要利用System.Collections.Generic命名空间下面的List泛型类创建集合,语法如下:

    基本使用如下

    1. //对象初始化器赋值
    2. List<string> list = new List<string> {
    3. "1",
    4. "2",
    5. "3",
    6. "4",
    7. "5",
    8. };
    9. //增加
    10. //list.Add("1");
    11. //list.Add("2");
    12. //list.Add("3");
    13. //list.Add("4");
    14. //list.Add("5");
    15. for (int i = 0; i < list.Count; i++) {
    16. Console.WriteLine(list[i]);
    17. }
    18. Console.WriteLine("******************");
    19. //根据索引插入
    20. list.Insert(2, "测试");
    21. for (int i = 0; i < list.Count; i++)
    22. {
    23. Console.WriteLine(list[i]);
    24. }
    25. //移除指定的索引数据
    26. Console.WriteLine("******************");
    27. list.RemoveAt(0);
    28. for (int i = 0; i < list.Count; i++)
    29. {
    30. Console.WriteLine(list[i]);
    31. }
    32. //移除的数据名称
    33. Console.WriteLine("******************");
    34. list.Remove("测试");
    35. for (int i = 0; i < list.Count; i++)
    36. {
    37. Console.WriteLine(list[i]);
    38. }
    39. //修改指定索引的数据
    40. list[2] = "测试2";
    41. //修改后
    42. Console.WriteLine("******************");
    43. for (int i = 0; i < list.Count; i++)
    44. {
    45. Console.WriteLine(list[i]);
    46. }
    47. student student = new student();
    48. student.age = 18;
    49. student.name = "小明";
    50. //数据类型弄成对象形式
    51. List students = new List {
    52. student,
    53. student, student, student, student, student, student, student, student, student, student
    54. };
    55. foreach (student Student in students) {
    56. Console.WriteLine(Student.age + "岁");
    57. Console.WriteLine(Student.name+"");
    58. }

  • 相关阅读:
    库函数的模拟实现
    MongoDB基础操作--基础工具使用
    数据库基础小练习
    设计原则之【里式替换原则】
    redis做缓存,mysql的数据怎么与redis进行同步(双写一致性)
    Leetcode 438. 找到字符串中所有字母异位词
    Redis常见面试题
    MySQL优化(四) binlog的应用
    C++是不是最容易产生猪队友的编程语言之一?
    flutter学习之控件的使用
  • 原文地址:https://blog.csdn.net/dawfwafaew/article/details/126192636