Skip to content

江南小碧的C#教程:4、各种集合类与循环 #22

Open
@bieberg0n

Description

@bieberg0n
Owner

C#的集合类中包括列表、字典和其他常用的数据类型。

列表

C#中比较类似于Python里的list的数据类型是ArrayList。
以下代码展现了ArrayList的增删改查:

using System;
using System.Collections;

class HelloWorld {
    static void Main() {
        ArrayList list_1 = new ArrayList(); // 新建列表

        // 在列表尾部添加元素
        list_1.Add(1);
        list_1.Add("abc");
        list_1.Add(true);

        // 查看任意一个元素
        Console.WriteLine(list_1[1]);

        // 查看列表长度
        Console.WriteLine(list_1.Count);

        // 修改元素
        list_1[1] = 2;

        // 插入元素
        list_1.Insert(1, "ABC");

        // 删除元素
        list_1.RemoveAt(2);
    }
}

更多关于列表和类似数据类型的资料见C#中数组、ArrayList和List三者的区别

字典和其他

参见C#中的Dictionary字典类介绍
C# 集合(Collection)

循环

通过循环可以方便地把列表中的每一个元素打印出来。

using System;
using System.Collections;

class HelloWorld {
    static void Main() {
        ArrayList list_1 = new ArrayList(); // 新建列表

        // 添加元素
        list_1.Add(1);
        list_1.Add("abc");
        list_1.Add(true);

        foreach (var i in list_1) {
            Console.WriteLine(i);
        }
    }
}

输出:

1
abc
True

foreach...in类似于Python的for用法。C#还有原始的类似C的for循环。

用for循环计算1+2+....+100:

using static System.Console;

class HelloWorld {
    static void Main() {
        var sum = 0;
        for (var i = 1; i <= 100 ; i++) {
            sum += i;
        }
        WriteLine(sum);
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @bieberg0n

        Issue actions

          江南小碧的C#教程:4、各种集合类与循环 · Issue #22 · bieberg0n/blog