When using System.Linq.Dynamic, how do you round nullable decimal values?

c# dynamic dynamic-linq linq math

Question

When I try to use Math.Round(x,0) or Math.Round(x) I get error System.Linq.Dynamic.ParseException: No applicable method 'Round' exists in type 'Math'.

When I try to use Convert.ToInt64(x) I get exception Expression of type 'System.Nullable`1[System.Decimal]' cannot be used for parameter of type 'System.Object' of method 'Int64 ToInt64(System.Object)'

When I try to use (long)x I get exception No property or field 'long' exists in type 'DynamicClass1'.

1
0
1/4/2012 9:15:44 PM

Popular Answer

Your problem is that Math.Round requires a decimal not a (nullable) decimal?.

You could do something like this:

decimal?[] values = { 0.1M, 0.123M, 0.456M, 0.345M, null, 0.2M, 0.01M, null, 0.367M };

var grouped = values.GroupBy(x => x.HasValue ? (decimal?)Math.Round(x.Value, 1) : null);

foreach (var group in grouped)
{
    Console.WriteLine("Group {0} has these members:", group.Key == null ? "Null" : group.Key.ToString());
    foreach (var groupMember in group)
    {
        Console.WriteLine("> {0}", groupMember == null ? "Null" : groupMember.ToString());
    }
}

This retains the null values, mapping them onto a group with the key null. If you don't care about these, you could do something like this instead:

var grouped = values.Where(x => x.HasValue).Select(x => x.Value).GroupBy(x => Math.Round(x, 1));

so that everything will be non-nullable decimal.

1
1/4/2012 11:27:49 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow