C# Set collection? - net - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore C#Setcollection? AskQuestion Asked 13years,5monthsago Modified 3years,10monthsago Viewed 415ktimes 536 53 DoesanyoneknowifthereisagoodequivalenttoJava'sSetcollectioninC#?IknowthatyoucansomewhatmimicasetusingaDictionaryoraHashTablebypopulatingbutignoringthevalues,butthat'snotaveryelegantway. c#.netcollectionsset Share Improvethisquestion Follow editedAug22,2013at10:13 OmarKooheji askedOct8,2008at16:33 OmarKoohejiOmarKooheji 52.6k6666goldbadges179179silverbadges237237bronzebadges 0 Addacomment  |  7Answers 7 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 427 Ifyou'reusing.NET3.5,youcanuseHashSet.It'struethat.NETdoesn'tcaterforsetsaswellasJavadoesthough. TheWintellectPowerCollectionsmayhelptoo. Share Improvethisanswer Follow editedMar1,2012at20:10 Sam 26.2k1212goldbadges7171silverbadges9999bronzebadges answeredOct8,2008at16:36 JonSkeetJonSkeet 1.3m817817goldbadges88958895silverbadges90319031bronzebadges 8 17 IsuspectthatSetisakeywordinsomelanguages,whichcouldcauseissues. – JonSkeet Jun24,2009at8:10 5 @Manish:Noit'snot.Seesection2.4.3oftheC#3spec.Itonlyhasspecialmeaningforproperties. – JonSkeet Apr17,2010at6:40 31 ThereasonforcallingitHashSet,insteadofjustSet,isthesameasinJava-"Set"describesaninterface,whereas"HashSet"describesanimplementation-specifically,thisisaSetbackedbyaHashMap.Inthisway,weknow(orshouldstronglyexpect)thatinsertandaccessshouldtakeO(1)accesstime,vsa"LinkedListSet"whichwouldleadustoexpectinsertandaccesstotakeO(n)time. – DavidSouther Jul16,2010at16:16 6 whatdoyoumean".NETdoesn'tcaterforsetsaswellasJavadoesthough."?IsthisSetsomehowimperfectcomparedtoJava's? – LouisRhys Feb28,2011at3:13 37 @Louis:WhichSetareyoutalkingabout?JavahaslotsofdifferentimplementationsofSetforvarioussituations..NEThadonein.NET3.5(HashSet)andtwoin.NET4(HashSetandSortedSet).Thefactthatwehadtowaituntil.NET3.5tostartwithisprettysurprising. – JonSkeet Feb28,2011at8:20  |  Show3morecomments 175 TryHashSet: TheHashSet(Of T)classprovideshigh-performancesetoperations.Asetisacollectionthatcontainsnoduplicateelements,andwhoseelementsareinnoparticularorder... ThecapacityofaHashSet(Of T)objectisthenumberofelementsthattheobjectcanhold.AHashSet(Of T)object'scapacityautomaticallyincreasesaselementsareaddedtotheobject. TheHashSet(Of T)classisbasedonthemodelofmathematicalsetsandprovideshigh-performancesetoperationssimilartoaccessingthekeysoftheDictionary(Of TKey, TValue)orHashtablecollections.Insimpleterms,theHashSet(Of T)classcanbethoughtofasaDictionary(Of TKey, TValue)collectionwithoutvalues. AHashSet(Of T)collectionisnotsortedandcannotcontainduplicateelements... Share Improvethisanswer Follow editedOct1,2016at20:26 gnat 6,210103103goldbadges5252silverbadges7272bronzebadges answeredOct8,2008at16:35 LeahnNovashLeahnNovash 2,74122goldbadges1919silverbadges1717bronzebadges 1 9 Unfortunately,HashSetsweren'taddeduntiljustrecently.Ifyou'reworkinginanolderversionoftheframework,you'regoingtohavetostickwithyourmungedDictionary<>orHashtable. – GregD Oct8,2008at16:36 Addacomment  |  31 Ifyou'reusing.NET4.0orlater: InthecasewhereyouneedsortingthenuseSortedSet.Otherwiseifyoudon't,thenuseHashSetsinceit'sO(1)forsearchandmanipulateoperations.WhereasSortedSetisO(logn)forsearchandmanipulateoperations. Share Improvethisanswer Follow editedAug31,2013at22:17 answeredAug31,2013at18:01 DerekWDerekW 9,26855goldbadges5252silverbadges6666bronzebadges Addacomment  |  15 IuseIesi.Collectionshttp://www.codeproject.com/KB/recipes/sets.aspx It'susedinlotofOSSprojects,IfirstcameacrossitinNHibernate Share Improvethisanswer Follow answeredOct8,2008at16:36 ChrisCanalChrisCanal 4,78799goldbadges3333silverbadges4545bronzebadges Addacomment  |  13 IuseawrapperaroundaDictionary,storingnullsinthevalues.ThisgivesO(1)add,lookupandremoveonthekeys,andtoallintentsandpurposesactslikeaset. Share Improvethisanswer Follow answeredNov26,2009at1:08 thecoopthecoop 43.9k1717goldbadges126126silverbadges184184bronzebadges 1 2 Youmustmeanit'sroughlyequivalenttostd::unordered_set.std::setisordered.Forexample,youcanquicklyfindthestartandendpointofarangeanditeratefromthestarttotheend,visitingitemsinkey-order.SortedDictionaryisroughlyequivalenttostd::set. – doug65536 Feb4,2013at7:43 Addacomment  |  12 HavealookatPowerCollectionsoveratCodePlex.ApartfromSetandOrderedSetithasafewotherusefullcollectiontypessuchasDeque,MultiDictionary,Bag,OrderedBag,OrderedDictionaryandOrderedMultiDictionary. Formorecollections,thereisalsotheC5GenericCollectionLibrary. Share Improvethisanswer Follow editedOct8,2008at16:50 answeredOct8,2008at16:38 dpandpan 5,32222goldbadges2525silverbadges2828bronzebadges Addacomment  |  -6 Iknowthisisanoldthread,butIwasrunningintothesameproblemandfoundHashSettobeveryunreliablebecausegiventhesameseed,GetHashCode()returneddifferentcodes.So,Ithought,whynotjustuseaListandhidetheaddmethodlikethis publicclassUniqueList:List { publicnewvoidAdd(Tobj) { if(!Contains(obj)) { base.Add(obj); } } } BecauseListusestheEqualsmethodsolelytodetermineequality,youcandefinetheEqualsmethodonyourTtypetomakesureyougetthedesiredresults. Share Improvethisanswer Follow editedFeb4,2012at23:01 answeredFeb4,2012at22:50 BobHeckBobHeck 1522bronzebadges 2 13 Thereasonyouwouldn'twanttousethisisbecauseList.ContainsisofO(n)complexitywhichmeansthatyourAddmethodnowbecomesO(n)complexityaswell.Assumingtheinnercollectiondoesn'tneedtoberesized,AddforbothListandHashMapshouldbeofO(1)complexity.TLDR:Thiswillwork,butit'shackyandlessefficient. – RichardMarskell-Drackir Feb24,2012at20:28 6 Sure,ifyourobjectsdon'treturnanappropriatevalueforGetHashCode,youshouldnotputthemintoahash-basedcontainer.ItwouldbebettertofixGetHashCodethantousealessefficientcontainer. – bmm6o Mar5,2012at17:40 Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedc#.netcollectionssetoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems GettingthroughaSOC2auditwithyournervesintact FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Visitchat Linked 0 WhatisthebestfitdatastructuretoworkwithSetsinC# 1 WhywasSetleftoutof.NETCollections? 1 HowtoconvertasetofenumerationrangefromDelphitoC#? 432 Define:WhatisaHashSet? 56 Istherea"Set"datastructurein.Net? 10 C#Array,Howtomakedatainanarraydistinctfromeachother? 29 Arethereanyimplementationsofmultisetfor.Net? 8 Whatisthebestcollectiontypetoeasilylookupvalueswithmultiple,identicalkeys? 6 InC#,isthereaqueuewhichcanonlyholdanobjectonceinitslifetime? 5 Whichdatastructure/classIcanusetorepresentone-to-manyrelation? Seemorelinkedquestions Related 894 Howdoyousortadictionarybyvalue? 2479 Deepcloningobjects 3229 Caseinsensitive'Contains(string)' 1076 Collectionwasmodified;enumerationoperationmaynotexecute 878 EfficiencyofJava"DoubleBraceInitialization"? 810 Distinct()withlambda? 623 WhatarethetruebenefitsofExpandoObject? 659 WaystoiterateoveralistinJava 676 HowtoconvertSettoArray? 1597 WhynotinheritfromList? HotNetworkQuestions Typingabashcommand,I'matitsthirdline.ButhowdoIreturntoitsbeginningtoeditsomethingI'vemissed? Inthesentence"Thetablewassetforlunch"is"set"averboranadjective? Reasonssomeonewouldavoidworkingoncareergrowth HowWouldHumanoidsFormTheirOwnGems? Sandboxoverflow Whataresomegoodoptionsformuseums/memorialstolearnmoreaboutthehistoryofJimCrow/lynching Did"fossil-fuelpollution[kill]threetimesasmanypeopleasCOVID-19did"in2020? Whatisagoodsoftwaretomaketechincaland/orschematicillustrationsaboutspace/orbitaldynamicstopics? Separatingbusinesslogicfromdatatemptsmetouseinstanceof FrameStringsthatcontainnewlines Isthereaconventionfordocumentingaschematicwithnotes? WhydidYon-RoggwanttofightCaptainMarvelhand-to-handafterhecrashesonEarth? WhydosomanystandardsforJSONAPIresponseformatscontaina"success"propertyintheresponsebodyinsteadofjustusingHTTPstatuscodes? Whydoesn'ttheUSsendairplanestoUkraine,whenRussianssentMIGstoVietnamduringVietnamwar? Iturnedabreakeroff,andnowthesecurityalarmsystemwon’tstopbeeping StopPipesFromPullingThroughTheWall GeometryNodes:Howtomaketubefromcurve EnigmarchDay2:Rhyme ITstaffsaidthatLinuxcannotconnecttotheschool'sInternet(EduStar)andrefusedtotry NFA:Howdoesitfunctionwithempty-stringmoves? ReplaceallbutcoordinatesfromaWKTstring,includingclosingbracket')' EnigmarchDay1:Initial WeirdpowerlinesforS-100,whyno5V? Inacyberpunkworldwherecorporateupperclasscitizenscanworkvirtuallythroughimplants,whywouldtheybuildcorporatemega-skyscrapers? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?