个性化阅读
专注于IT技术分析

C#集合SortedSet

点击下载

C#SortedSet类可用于存储,删除或查看元素。它保持升序,并且不存储重复的元素。如果必须存储唯一的元素并保持升序,建议使用SortedSet类。在System.Collections.Generic命名空间中找到它。

C#SortedSet <T>示例

让我们看一个通用SortedSet <T>类的示例,该类使用Add()方法存储元素,并使用for-each循环迭代元素。

using System;
using System.Collections.Generic;

public class SortedSetExample
{
    public static void Main(string[] args)
    {
        // Create a set of strings
        var names = new SortedSet<string>();
        names.Add("Sonoo");
        names.Add("Ankit");
        names.Add("Peter");
        names.Add("Irfan");
        names.Add("Ankit");//will not be added
        
        // Iterate SortedSet elements using foreach loop
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

输出:

Ankit
Irfan
Peter
Sonoo

C#SortedSet <T>示例2

我们来看另一个通用SortedSet <T>类的示例,该类使用Collection初始化程序存储元素。

using System;
using System.Collections.Generic;

public class SortedSetExample
{
    public static void Main(string[] args)
    {
        // Create a set of strings
        var names = new SortedSet<string>(){"Sonoo", "Ankit", "Peter", "Irfan"};
        
        // Iterate SortedSet elements using foreach loop
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

输出:

Ankit
Irfan
Peter
Sonoo
赞(0)
未经允许不得转载:srcmini » C#集合SortedSet

评论 抢沙发

评论前必须登录!