Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegantly refactoring code like this (to avoid a flag)

Tags:

c#

.net

.net-4.0

I have a function running over an enumerable, but the function should be a little bit different for the first item, for example:

void start() { 
    List<string> a = ...
    a.ForEach(DoWork);
}

bool isFirst = true;

private void DoWork(string s) {
   // do something

   if(isFirst)
     isFirst = false;
   else
     print("first stuff");

   // do something
}

How would you refactor this to avoid that ugly flag?

like image 841
onof Avatar asked Sep 02 '26 11:09

onof


1 Answers

Expounding on Jimmy Hoffa's answer if you actually want to do something with the first item you could do this.

DoFirstWork(a[0])

a.Skip(1).ForEach(DoWork)

If the point is that it is separate in logic from the rest of the list then you should use a separate function.

like image 98
msarchet Avatar answered Sep 04 '26 01:09

msarchet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!