c# - Is there a way to handle any type of collection, instead of solely relying on Array, List, etc? -


this example method called "writelines", takes array of strings , adds them asynchronous file writer. works, curious if there interesting way support -any- collection of strings, rather relying on programmer convert array.

i came like:

public void addlines(ienumerable<string> lines) {     // grab queue     lock (_queue)     {         // loop through collection , enqueue each line         (int = 0, count = lines.count(); < count; i++)         {             _queue.enqueue(lines.elementat(i));         }     }     // notify thread has work do.     _hasnewitems.set(); } 

this appears work have no idea of performance implications has, or logic implications either (what happens order? assume allow unordered collections work, e.g. hashset).

is there more accepted way achieve this?

you've been passed ienumerable<string> - means can iterate on it. heck, there's language feature specifically - foreach:

foreach (string line in lines) {     _queue.enqueue(line); } 

unlike existing approach, iterate on sequence once. current code behave differently based on underlying implementation - in cases count() , elementat optimized, in cases aren't. can see if use iterator block , log:

public ienumerable<string> getitems() {     console.writeline("yielding a");     yield return "a";     console.writeline("yielding b");     yield return "b";     console.writeline("yielding c");     yield return "c"; } 

try calling addlines(getitems()) current implementation, , @ console...


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -