📜  C#|获取集合中包含的元素数<T>

📅  最后修改于: 2021-05-29 13:39:10             🧑  作者: Mango

Collection < T > .Count属性用于获取Collection < T >中实际包含的元素数。

句法:

public int Count { get; }

返回值: Collection >中实际包含的元素数。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to get the number of
// elements contained in the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of strings
        Collection myColl = new Collection();
  
        // Adding elements in Collection myColl
        myColl.Add("A");
        myColl.Add("B");
        myColl.Add("C");
        myColl.Add("D");
        myColl.Add("E");
  
        // To print the count of elements in Collection
        Console.WriteLine("Count : " + myColl.Count);
  
        // Displaying the elements in myColl
        foreach(string str in myColl)
        {
            Console.WriteLine(str);
        }
    }
}

输出:

Count : 5
A
B
C
D
E

范例2:

// C# code to get the number of
// elements contained in the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of ints
        Collection myColl = new Collection();
  
        // Adding elements in Collection myColl
        myColl.Add(2);
        myColl.Add(3);
        myColl.Add(4);
        myColl.Add(5);
  
        // To print the count of elements in Collection
        Console.WriteLine("Count : " + myColl.Count);
  
        // Displaying the elements in myColl
        foreach(int i in myColl)
        {
            Console.WriteLine(i);
        }
    }
}

输出:

Count : 4
2
3
4
5

注意:检索此属性的值是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.count?view=netframework-4.7.2