HashSet<T>不重复的无序列表
SortedSet<T>不重复的有序列表
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
//=============================【HashSet<T>】==============================
//-----------------添加
HashSet<string> test = new HashSet<string> { "a", "b", "c" };
if (!test.Add("a"))//如果列表中存在就不会添加,并返回false
Console.WriteLine("该元素已存在,不添加");
if (test.Add("d"))
Console.WriteLine("添加元素成功");
//-----------------比较
HashSet<string> test1 = new HashSet<string> { "a", "b", "c"};
HashSet<string> test2 = new HashSet<string> { "a", "b", "c","d" };
if (test1.IsSubsetOf(test2))
{
Console.WriteLine("test1的每个元素test2都有");
}
if (test1.IsSubsetOf(test2))
{
Console.WriteLine("test2相对于test1有额外的元素");
}
if (test1.Overlaps(test2))
{
Console.WriteLine("test2与test1有共同的元素");
}
//=============================【HashSet<T>】==============================
//------------添加集
SortedSet<string> sd = new SortedSet<string>(test1);//将test1中的所有元素添加到有序列表中
sd.UnionWith(test2);//将test2中的所有元素添加到有序列表中【结果会排除重复的元素,并排序】
sd.Add("aa");
//------------删除集
sd.Remove("d");//删除匹配的元素
sd.RemoveWhere(r => r == "aa");//删除匹配的元素
sd.ExceptWith(test1);//删除集
foreach (var item in sd)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。