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!

Advertisement

~ by interneth3ro on January 6, 2012.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

 
Follow

Get every new post delivered to your Inbox.

Join 40 other followers