c# - Is there a more efficient way to write this code -
i think title says all,
here's code :)
private void listboxcomponents_mousedoubleclick(object sender, mouseeventargs e) { object item = listboxcomponents.selecteditem; string name = listboxcomponents.getitemtext(item); if (e.button == mousebuttons.left) { (int = 0; < terrains.count; i++) { if (terrains[i].name == name) terrains[i].enableboundingbox(true); else terrains[i].enableboundingbox(false); } } }
i have allot of code throughout quite similar , i'm hoping theirs neater, quicker way acoomplish same thing. maybe linq?
thanks :).
you have not stated mean "more efficient", take liberty interpret "easier read , type":
you can replace loop:
for (int = 0; < terrains.count; i++) { if (terrains[i].name == name) terrains[i].enableboundingbox(true); else terrains[i].enableboundingbox(false); }
with one:
foreach (var terrain in terrains) { terrain.enableboundingbox(terrain.name == name); }
note in general, foreach
loops less efficient @ runtime for
loops. difference tiny , absolutely nothing worry except in more extreme real-time / high-performance scenarios. on positive side, end simpler source code.
by way, might better compare strings using string.equals(string, string, stringcomparison)
method, because makes more explicit culture , case sensitivity should used comparison.
as aside, have mentioned linq. linq bad fit here; let me briefly explain why: in theory possible write custom linq operator foreach
, accept action<t>
delegate. implemented foreach
loop invokes delegate each item in source sequence. write following one-liner:
terrains.foreach(terrain => terrain.enableboundingbox(terrain.name == name));
in opinion, plain foreach
loop more readable, though takes more lines of code. important, remember linq stands for: "language-integrated query". linq expressions should query data, not modify (i.e. have side effects). foreach
custom operator, however, side effects; that's why not fit linq paradigm , not included in framework.
(as final remark, answer code review. if desired, perhaps code review se site might have been more appropriate place post question.)
Comments
Post a Comment