c# - Compare and Remove List Items using For Loop -
i have download list , exclude list.
i want keep file2.zip
using loop.
however loop doesn't work correctly , keeps both file2.zip
, file4.zip
.
http://rextester.com/uwct32568
this example code want apply larger project.
i not want use download = download.except(excluded).tolist();
in case.
http://rextester.com/hbqzpc42707
list<string> download = new list<string>(); download.add("file1.zip"); download.add("file2.zip"); download.add("file3.zip"); download.add("file4.zip"); download.add("file5.zip"); list<string> excluded = new list<string>(); excluded.add("file1.zip"); // keep file2.zip excluded.add("file3.zip"); excluded.add("file4.zip"); excluded.add("file5.zip"); // remove excluded files download list // int count = download.count(); (int = 0; < count; i++) { // index out of range check if (download.count() > ) { // remove if (excluded.contains(download[i])) { download.removeat(i); download.trimexcess(); } } } // display new download list // download.foreach(x=>console.writeline(x));
- when removing, loop backward:
- use
hashset<string>
more efficient finding item at
implementation:
// items remove: excluded.contains(item) more efficient if excluded hashset<t> hashset<string> excluded = new hashset<string>() { "file1.zip", "file3.zip", "file4.zip", "file5.zip", }; (int = download.count - 1; >= 0; --i) if (excluded.contains(download[i])) // shall remove i-th item? download.removeat(i); // if yes, remove // if want trim list, not within loop, // remove required items , trim (once!) list download.trimexcess(); // not necessary, possible
edit: in (rare) cases when have to loop forward (e.g. if have remove items in order created) loop is
(int = 0; < download.count;) // please, notice, no increment here if (excluded.contains(download[i])) // shall remove i-th item? download.removeat(i) // if yes, remove else += 1; // if no, inspect next item
Comments
Post a Comment