Tech Tip: Quantize Values

So here’s some tech knowledge to throw out there. I found a need for a current project to take a collection of values (decimals, ints, nothing major), and only show a value if all values were the same. A quick search at stackoverflow got me started, so here’s what I have.
First, I’m using nullable values here because the current problem space requires nullable values. They’re not necessary, just what I had to work with. Here’s some code:

private decimal? QuantizeDecimal(IEnumerable<decimal> values)
    if (!values.Any())
        return null;

    decimal firstValue = values.First();
    return (values.Skip(1).All(x => x == firstValue)) ? firstValue : null;

So the idea is, if the collection is empty, return null (or whatever value indicates inequality for you). Grab the first value in the collection, then test to see if the rest of the values in the collection match the first one (first skipping the first value, obviously). In my case, a null value defines that there were values that didn’t match, so I don’t show anything. However, if all the values match, then I return that value to display on my form.

Questions, comments, concerns, suggestions for improvement, etc., please comment below!


~ by interneth3ro on January 6, 2012.

One Response to “Tech Tip: Quantize Values”

  1. I’ve been absent for a while, but now I remember why I used to love this website. Thank you, I will try and check back more often. How frequently you update your site?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: