c#中.clear()作用

C#List <T> .Clear()方法 (C# List<T>.Clear() Method)

List<T>.Clear() method is used to clear the list, it remove all elements from the list.

List <T> .Clear()方法用于清除列表,它从列表中删除所有元素。

Syntax:

句法:

    void List<T>.Clear();

Parameter: It accepts nothing.

参数:不接受任何内容。

Return value: It returns nothing – it's returns type is void

返回值:不返回任何内容–返回的类型为void

Example:

例:

    int list declaration:
    List<int> a = new List<int>();

    adding elements:
    a.Add(10);
    a.Add(20);
    a.Add(30);
    a.Add(40);
    a.Add(50);
    
    removing elements:
    a.Clear();
    
    Output:
    None

使用List <T> .Clear()方法从列表中删除所有项目的C#示例 (C# Example to remove all items from the list using List<T>.Clear() Method)

using System;
using System.Text;
using System.Collections.Generic;

namespace Test
{
    class Program
    {
        static void printList(List<int> lst)
        {
            //printing elements
            foreach (int item in lst)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //integer list
            List<int> a = new List<int>();

            //adding elements
            a.Add(10);
            a.Add(20);
            a.Add(30);
            a.Add(40);
            a.Add(50);

            if (a.Count > 0)
            {
                //print the list
                Console.WriteLine("list elements...");
                printList(a);
            }
            else
            {
                Console.WriteLine("list is empty");
            }

            //clear all elements
            a.Clear();
            
            //list after removing the elements
            if (a.Count > 0)
            {
                Console.WriteLine("list elements after removing elements...");
                printList(a);
            }
            else
            {
                Console.WriteLine("list is empty");
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

输出量

list elements...
10 20 30 40 50
list is empty


翻译自: https://www.includehelp.com/dot-net/list-t-clear-method-with-example-in-c-sharp.aspx

c#中.clear()作用

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐