当我尝试使用Math.Round(x,0)或Math.Round(x)时,出现错误System.Linq.Dynamic.ParseException: No applicable method 'Round' exists in type 'Math'
。
当我尝试使用Convert.ToInt64(x)时,出现异常Expression of type 'System.Nullable`1[System.Decimal]' cannot be used for parameter of type 'System.Object' of method 'Int64 ToInt64(System.Object)'
当我尝试使用(long)x
异常No property or field 'long' exists in type 'DynamicClass1'
。
您的问题是Math.Round
需要一个decimal
而不是一个(可空的) decimal?
。
您可以执行以下操作:
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());
}
}
这将保留null
值,并使用键null
将它们映射到组中。如果您不关心这些,则可以执行以下操作:
var grouped = values.Where(x => x.HasValue).Select(x => x.Value).GroupBy(x => Math.Round(x, 1));
所以,一切都将是非空的decimal
。