Download as pdf
Download as pdf
You are on page 1of 9
00 CODE PROJECT ‘ces Languages CF Aplatons List vs IEnumerable vs IQueryable vs ICollection vs [Dictionary [Mahsa Hassankashi Nov 2012 cPOL He He He aa rates ‘This ticles ane ofthe fst source that collec al of data structure from Array, IQueryable,Iénumarable and compares these ones cleat ‘ist vs tEnumerable vs IQueryable vs ICellection vs IDetionary - 494.3 KB Demo For Data Access Layer a a ea ED | TT eT Sara aT sama — rae) a aR ATT Br [eee fomtmeresiey a aa ena ean Wana er Sec es TTT RT| | ERESBET—| MeaSE Ren aE | NOT SRE] BEATA] Se] ERR RTD ERATE TRS RET | ST ERT — eee SS ETS a TT Collection Set or group of records which makes one mesningfl unin fetch nd modfetion progress we ned aprons container o store them temporary if Appropate container depends on 1 Our acon ch we want ado on dats ( just read do modification such as inser, dele, ec) 2 Number of records whch shouldbe wansfer Array 1. Feed Lengtn-» dificuk to change the number of count2. Type Safe-> you determine ts type at coding process it ths better performance due to da not ensure tne at run ine to specie type container) 3. Use “for” keyword to fil and iterate through array Atay s faster than Avast because its fixed sized and strong type, so it neds less memory {us tits datatype and dimensions determineé Pfft as Assting As sting As ting 36 65 obvious tht strhery (= UB. Saedise 3 Fie hae steinet] strray = ne strine i615 for (ine 2 8; 1 e185 409 e 1 (stseray tt) stomrayis] = (ea) Testring(ds > MelUstontreay-Tersclesrh {hieLUsatontray-Sataning ° ArrayList “Lites nt have spec langth > Ii possible to grow dats, ts good feature because fa the fist we ar nt thay tose abou length of electon 2. Aral does not have any spac ype and it willbe determined trun time, advantage is whan you ae nt sure ‘out Spe of eta unt in rn time user determines it nd its aiscvantage is to reduce performance by consuming time, 50 se itjust uhen you need i its tke varable or abject 5. Use foreach” keyword fr iterate through it t f AsstringAsintoger went reduce « > public roduc (string Cae, string None) ¢ > ace (get: sets) Rave Casts sets > , ‘Asrylist can accept sting. integer and decimal tthe same time 1218 07 obvi tht srbrokist GB sting it) obec? dein? <=> 07 strongly pe 2D noespace: syscen.cottections Syston caltecetone ArrayList strrrayLise = now Syten-Collections AvayLtstQ)s ‘Zaps: Lina tuergonte type of esto ts fot specie Pantne defer support Setar sstehed( names, 77 “hataa": string Seomraytisecnadty 77 TS 1 integer Stem isteaatovinns 7 eas: deel ‘shse-Ussboutrayc tet oaasource = nulls ‘hiscUsatontreay let teens theseO) {Th Lsttonarayclst Dntsaouree © atederayLists SNE Ltstonteayc fet otasonets sean ste, , i lf fr rapt ome ct re hs fabestgee so 4 Spas «Bb, 1 eT Sac 3m my syrtencallecetns.Arrayist cnjrrayList = now Syten Collections AvayLtst(s objernytist Atlee Product (2001, “Chale): Seyeenyctsssactfy poacact(-ise2")“so"s>))y hyernylist acres Preset (1603, “Carpe 39s his aropbountstarraystabjeet.atasource = rl hs. Orootowtstheraystth ect Tans, Car ‘hie Drepbowntitanrayisttbjertastascure = ejay Lf nog ono Object of Aero) List ts dKfFteuLt, you hove to Find your spectfte (eon by tne reduc atten (rrocucthonjernylisea}s Shparayitet Renova onan) - ‘Ste oeptounteherayitaoseee oatatereiela {R16 Orton itarray tthe Oetevauer tele {h roppomtsearrayLstib ject oetabind0): Shir Lanlvicuraytsetonject-oxtasouree = bjteeayst; mesiavieweayt stObectbaa0iM6 HashTable (ona 23) Sot", 25) TAG NOF abso that strarroyist “Ua. Sttne> Ges Soja? aectae? on OBEET?? => nar strongly Type Upvamabie salve sta proion in Aeraylist ater we are Looting for specific tten ‘Zonasncante Gecicate 6 hey for toch tees, ten Finding Veen 1 soster and faster Syston collections. hashtable abjashrable = ou Systn.Calectlonssheable(); chgahebe ase" "tes ‘horasnaniecagd(983", Carget bs {h!Dropbomt stant aie. een: leer ( SN brestomstcataie:oatstouee © choshrabe; “fnaing en ts ester you ost need to povne CC by call {05 hey Ghpitaateshenvet i002), SN goon etacntae butane); Stack stack ura LastinFrstout rushto Pop om Topetstack Topo sack Lastin lastout Gs Fs "oars "hana Tense “Cosme Hassan” "Hossein "Mahsa Stack - Push [/Stock a LF Last in Frat Out ‘syrcen cat lectine, Stack obsStacaush + ae SystemC tions. st30405 Loy ruth seehos yay con insert to ot the tap of the stack Gesbesesouan-poet makes) BEtadoumh: ant anarcahis ‘hie Usehoustat outsource = ebseackPus.Takeray(j ENSLUsshowstock oot) Stack - Pop. syste colectons. Stack obg5t2kPep = non Systen.ollectionsSt3CKOs cnsstsston.rurnnanes") ksstaaoen Pusm(-nansansht")s L/ap ee wetbod you can cenone (en $700 the top of the Stuck > Last On FL Ue CASE leap faces ebiesehrap-Popt)faseengt)s ‘ths Lsthonseack.ontaSouree = ebstactPo.Tarray(); SM LuSnoestek outa) Queue ate Queue is FIFO [Dequewe from cm fn ftot — G G> Queue - Enqueue Loveue e F1fo: Frat in Heat but systenoltectons. Queue obfdueve = ron Systen-CobLctions. Queue); Loy tngucse method you ca insert ‘ton at the 0 of the Queue Sejeuve- nur nan", Shjgueve: moet nossonashi"): Sbjgeve_eomuece cones} ShsguvesemureeC verse") spsectmguave Tose =“ ‘hie Uethowgine ontaSouree = ebsQaue-Tokray()s EN Usshonduee ootonindt): Queue - Deque Systen col2ectone.Queve objQueve = nex Systen.Coections. Ques onjquve. enqueue mane"); Shlgevesermoeetnossonashi"D; Ghjgueve. mune Conese} Shjgeve.enmuece verse) Loy eguae metho you can rerove Stan fro the BEGINING of the Queue -> First tn First out FEO (soe leu ontoehjqean-Seqeuet) Tosesnati ‘this Listonqueve.ootasaurce = sbjqueue-Tokray()5 SNELL fskonguew Sota) List Why we need Uist? 1st does not have specific ength-> tis porible ta have data without knowing ite si, iis good feature because of atthe fist we are not likely to sure about length of cllection. 2st nas Specie type so tis strong type. therefore it has better perfomance and hign speed in comparison wth ArrayList and reduce unwanted enor in compile me 5. Use foreach cron for trate trough it Lateroduc| o Name Price ‘Quantity TOOT Tea 70005 3 007 Cale 72005 7 testing (aise [ross [rasan [ese [ms] {1a seray bs strong roe [ieSke forays len no Binarston Sjetencollecttonescanenescistestring> stList = ne (istestsne> Os serttsesaatnsseds SUSE eal haasanat"}: SUES steListaatdcverse"ds {his Liston istenerde tating: . Syston ont Stringiuilder ste = ou Syeton. Tent Stringbut6er0)s foreach (var Star sn strLit) c serpent”. = Sten: n Arssciitiet-toxt = stetostrineOs List Why we nee Ist” st i an interface of st (es evrything that Ust does and to aoserve polymarphsm inorder to decouple and controlon add or remove method that implement on the cient side, everthing else ae similar to ist. |wneneverwe want to change on same operation Tit” low us todo that eal witha lest changing in the whole of codes list cannot be instante fom ist st shouldbe instantiate am ist syrton collections Conese tListesteing> setlist = nou ListesteiapsQ)s Difference between Abstract and Interface 1 Abstract inherit fom just one class but Imerface implemen from one or more interfaces ‘2 Abstract can have non concrete method (expand method) but you have to define just signature inside interface Snsde Abstract cass you can define variable and value but you ate not allowed to define vtabe ini interface ‘4m abstract dass can have constructor but inside interface you are not alwed to define constructor ‘You can wite scope for member af interface As {mentioned that how 3 class cannat be driven from tw clase it just can be den fom onl one css 50 Unenever you wart to dive am two dlassitsnot posible to inher fom two abstract dass but its possible to delve from one cats and another one lista interface. Laterin ture you decide add some features on your class and inherit tram anathar cas. So because ofthis eason ‘ae aly prefer o use interace of collec so thatf you want fo change your code and enhance it ables is possible te grow it, ‘on the other hand ntr‘ace keeps your program extensible and Decouple The classes are independent fom each ‘others err, exception and falure wl happen rarely in fture changing cose Pelymorphm: When you ae using interface you absolutely abterve and da polymorphism and oop. means ‘eneapulate your designer. interface means 3 point o 3 node to join two pat to each other it means making low ‘dependency from two pat and make a joint section to make fleible change in future {fest can vot be instantiate fron TUst $0 1 should be twstonttete from List ‘Spacencstleceons.coneriesitistesteing> skrdutet © ow UistatranpoOs stettast.adg¥ansa"; Soltisecadutnancangenteys Hetsse ase coon) Seitist-aas-verse)) {he Liston istenerdebtatine ° Systen Text Stringiuilder ste =u Syston Tent Stingbuth0erQs (foreach (van Aton sn steTsn) t sercpoand(™ + Stans > sectostesne Us smiar to List but wth tis ference that we prefer fo use INTERFACE instead of abstract in programming because future changing #35) lEnumerable ‘numerable's suitable jus for iterate through collection and you cannot medi (hdd or Remove) itIEnumerable bring [AL data from server to lent then fer them assume that you have alot of records se FEnumeable puts overhead on your memory Ce ang A data fom table tole [ABthenfiter ther (/Mowerabie ca not be sestontiate froe fumerable, 20 £¢ should be Snatantiate fron List ‘Syren al lectianescarerse.straveranlecenployet> eapifnurershe = sou Listetapayee> tee Employer (10'* dois, nanewbeher Dy en Eoloyee (1B © ez, on ployee (1D > is, % et notonee (1D > 386, Aone = “Technet” ) » hiverigveaitnmersbie-osapingQs ‘yaten text Stringiuilder ate = neu System text Stringoutlder()s ‘foreach (Enployee tenn enplenuersbte) see ctppand(” 5“ StentD «estan nae) ‘ose TEwnerabie. Text = str TOstetng(ds IQueryable sale“ from table where 978 Ere ring UST Filtered data rom tate Deed rhea Follow “Enty Framework Databases” fom this atl for making DBContext araacesstat ties ctx = nau ostaecesseesttes(}s or etn now DrmceessemstiesO Date Access stterence between IQueryabe a ehaecActiaplojeh moerYlegns le ~ face (aabeGeninyl ti acing — ALL conde fron server => to client then Gigse col a as er te emia = ron ain cx aloes Sslece m-TOLdet0) 11s can nat tnstanttate Tqueyeble Iquerybieetnployes queryLQveryeblerns oeing at ote cacnd fron zener 3 29 elie auerytqurysnle = (tron w in cox eployees Taeran his .GriviewlQuerysbleOntaSouree = querylQveryablesTList()s his GriieatQueryoke-DeteGind) attterence between tqeryable snd tener shou cov ansconiate Henrersne ren Cie {enaneraniectyplyeed quryitraerabie + bw UistcErployee() 5 ‘ortog Ai. veconde fron server ==> to clint then Ftlter collection ‘rerylinmerobie= {fron tn etx aployes Setee"a)eTouseeds {100 ca oot instantiate query eeryablectoloyee> uerylQveryabieen ‘ering just ON record fron server <-> to client sseetrate ee in eto mae ‘shis-oeavseutquryanleostasource ~ gueryiuaryable.Tol e805 {his oravicutQveryonte. takings ICollection 1st and iallection ae sila to exch other but with the one eliference that you can finds] => index Based you can NOT find iCllection i] > Not index Based ts lr) ali et ‘eect gare retin Uo Kins tae /1sst (indexer ord Nasty) vs Kattection franconly on Mes) {ieshiecton ton oat be inatareiate (oon ealleceian 20 tt stnulé be Snetarate (con Sot Specencaliecttone cane: teollectioncrtring) streollection new (istertriMp; Poitainection suena he Ferialisceion ase nassontsen") sieawrstnete® ‘his usstoriclleetion oaanineO; i, Speten fvesSerngauiioe str» he Syst. TostStingbut6ort); ‘areach (vat Item In stricellectio) stecapandt™ > + Aton > Unis amicalection. tors str Tasting): Sjatenatdect ic tLitstnploye> sbi 2 shjitiet = {eron in cox inployers ° Seite aj tecist: Enploye obj ~ nsnlist.tare(t > Sshane = “Sart). FlestoefauieOs ine esatSare ae jiiseInseso¥(ebj}s ihe else = opatsee court spicelestionte® Sjecen a! lecetne.canerse.tCollectionceyplayte> icoliection = paw Lseteemployees(); ‘hyitoliection » {iron ein ctr eqployeer selec a} folie) epee engi = oven er nine we saa erro: 1170 Sederstessconlecticn + sbjic.tneeot {abst {oe extaltoction = cseoliecien Cours Dictionary Dictionary is sina to HashTable but its GENERIC Lposcetonary con snatantiate fron Osctionery , Otctonary 1s stlar 9 Heshable [Pics Waahtode' jou con rd sbect 87 Cs be Sjaten cai lecetonu canerseolctionsrycine,stringe™> objOtetorary = neu DLctonarycns, sts cnjoteronary.t(nenn, wanes") Shpotetionarysa( ea, -vossontasht"); chiotetonary adie, “esnseverse} steing ser = obspictionary1002}5 hse-Utsgowteeonary ostasaurce = onsbtetonsrys {his Lsthowtettonary. dtabird()c/int dene [MV Tutornk htp//technicl cosmicverse.info/Artcle/Index/3. Data Access Layer Tutorial http://technical.cosmieverssinfo/Artile/index/ References tpn codeprjectcom/Arscls/732425/lEnumerable-Vs-IQueryable tpn dotnet-ticks. com Tutoriaing/SV160612-IEnumerable-VS-IQueryable hm ‘tp cbudiobemasconich/2013/07/22)when-o-use-enumerabledealecton-is-andlst Feedback Feel feet leave any feedback on this ticle ti pleasure to see your comments and vote about this code, Ifyou have any questions, please donot estate to ask me here License ‘This article, alongwith any associated source code and les, is licensed under The Code Project Open License (CPO!) Share About the Author Mahsa Hassankashi Sofware Developer ran fslamic Republic O9 = {have been working with Net ramewore for7 yeas. 1 lke t challenge with complex prablem, then make it easy for using everyone This the bes joy ICT Master stodent at University of Ager Diamond is nothing excep the pieces af the coal which have continued their cts all they have become Diamona tpyiwencosmicverseintor Inepyfwwtachnicalcosmicverseinfo Follow on Bie B kein Comments and Discussions ist messages have bee posted ft acest p/w codepreetcomyAice/ 48289 TEnumerbe vs 1Queyele ws ICaecony topos sven commas on ths ace ole hee ogo it ew swith messages, eran Jaret [>a tewsct ie Noble Saal este ceprgh 234 Maan te ‘webs [2b aes ian ope 2e eoming acai 6 coco oananie

You might also like