您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“C#的set怎么使用”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C#的set怎么使用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。
包含不重復(fù)元素的集合稱為“集(set)”。.NET Framework包含兩個(gè)集HashSet<T>和SortedSet<T>,它們都實(shí)現(xiàn)ISet<T>接口。HashSet<T>集包含不重復(fù)元素的無(wú)序列表,SortedSet<T>集包含不重復(fù)元素的有序列表。
ISet<T>接口提供的方法可以創(chuàng)建合集,交集,或者給出一個(gè)是另一個(gè)集的超集或子集的信息。
var companyTeams = new HashSet<string>() { "Ferrari", "McLaren", "Mercedes" }; var traditionalTeams = new HashSet<string>() { "Ferrari", "McLaren" }; var privateTeams = new HashSet<string>() { "Red Bull", "Lotus", "Toro Rosso", "Force India", "Sauber" }; if (privateTeams.Add("Williams")) Console.WriteLine("Williams added"); if (!companyTeams.Add("McLaren")) Console.WriteLine("McLaren was already in this set");
IsSubsetOf驗(yàn)證traditionalTeams中的每個(gè)元素是否都包含在companyTeams中
if (traditionalTeams.IsSubsetOf(companyTeams)) { Console.WriteLine("traditionalTeams is subset of companyTeams"); }
IsSupersetOf驗(yàn)證traditionalTeams中是否有companyTeams中沒(méi)有的元素
if (companyTeams.IsSupersetOf(traditionalTeams)) { Console.WriteLine("companyTeams is a superset of traditionalTeams"); }
Overlaps驗(yàn)證是否有交集
traditionalTeams.Add("Williams"); if (privateTeams.Overlaps(traditionalTeams)) { Console.WriteLine("At least one team is the same with the traditional " + "and private teams"); }
調(diào)用UnionWith方法把新的 SortedSet<string>變量填充為companyTeams,privateTeams,traditionalTeams的合集
var allTeams = new SortedSet<string>(companyTeams); allTeams.UnionWith(privateTeams); allTeams.UnionWith(traditionalTeams); Console.WriteLine(); Console.WriteLine("all teams"); foreach (var team in allTeams) { Console.WriteLine(team); }
輸出(有序的):
Ferrari Force India Lotus McLaren Mercedes Red Bull Sauber Toro Rosso Williams
每個(gè)元素只列出一次,因?yàn)榧话ㄒ恢怠?br/>ExceptWith方法從ExceptWith中刪除所有私有元素
allTeams.ExceptWith(privateTeams); Console.WriteLine(); Console.WriteLine("no private team left"); foreach (var team in allTeams) { Console.WriteLine(team); }
讀到這里,這篇“C#的set怎么使用”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。