7

I want to print a percentage value in one (or more) integer intervals. The code below describes object.ProgressChanged as an EventHandler<EventArgs> and maxPercent as a global int variable.

object.ProgressChanged += (sender, args) => (
    if (maxPercent < ((int) args.ProgressPercentage)) {
        maxPercent = (int) args.ProgressPercentage;
        Console.WriteLine(maxPercent + "%");
    }
)

I can easily solve this problem by doing this:

object.ProgressChanged += (sender, args) => aFunction(args);

where aFunction contains all the same code after the => operator in the first piece of code.

I am looking for a more elegant way to approach this problem, if possible, in one line. Any tips?

budi
  • 6,351
  • 10
  • 55
  • 80
  • If you insist on keeping Console.WriteLine, your hands are pretty much tied to what you have now. – David L Jul 20 '15 at 23:30
  • "this problem"? what problem? – Dave Cousineau Jul 20 '15 at 23:30
  • What don't you like about the second solution? – Loocid Jul 20 '15 at 23:30
  • I was just wondering if there was a way to write this in one line. I guess it's not really a "problem," it's more just out of curiosity. – budi Jul 20 '15 at 23:32
  • I'm unclear on what you want to achieve. Do you want to compress your 3 lines of logic into one? That will result in a mess, and it's pointless. – usr Jul 20 '15 at 23:32
  • Can you please define "one line"? Frequently "one line" is used as equivalent of "single statement/single expression" irrespective how long it is... Also is method inside condition always returns `void` (like `Console.WriteLine`) - otherwise you can't easily use `?:` to create single statement... – Alexei Levenkov Jul 20 '15 at 23:35
  • Oh, is your problem how to write the first code snippet in a valid way? – usr Jul 20 '15 at 23:35
  • @usr Yes that is what I wanted, I realize that I was not clear at all in my original post... Looks like Jeff Mercado already posted the answer I was looking for. – budi Jul 20 '15 at 23:38
  • The duplicate this was closed against is a completely different question, by the way. – Rob Jul 21 '15 at 00:10

1 Answers1

9
object.ProgressChanged += (sender, args) => {
    maxPercent = Math.Min(maxPercent, (int)args.ProgressPercentage);
};

As Jeff pointed out you should use { } for a multi-line lambda.

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101