Round list of decimal lists

I'm trying to find a shorter way of rounding each item in List<List<decimal>>

and wondering if there is a way to shorten it using Linq?

I have tried several ways such as

List<List<Decimal>> masterList = dataSet
.Select(x => x.Values)
.ToList()
.Select(i => Math.Round(i, 2));  
/// THIS GIVES AN EXCEPTION (CANNOT CONVERT FROM System.Collections.Generic.List<decimal> to 'double'

      

Is this my current way of doing this?

List<List<Decimal>> masterList = dataSet.Select(x => x.Values).ToList();

foreach (var list in masterList)
{
    for(var i = 0; i < list.Count; i++)
    {
        list[i] = Math.Round(list[i], 2);
    }
}

      

+3


source to share


2 answers


To complete the assignment, use Decimal.Round

, and not Math.Round

:

masterList = masterList.Select(
    x => x.Select(y => Decimal.Round(y, 2)).ToList()
    ).ToList();

      



Edited with number of decimal places (2). Also, the problem seems to be in the instructions LINQ

instead of using Math.Round

or Decimal.Round

.

Decimal.Round

is my preference for the case decimal

, especially if the value decimal

needs to be converted to the shortest int

. The format is very convenient:Decimal.Round(val)

+3


source


Here's an example of how you can do this using LINQ:



List<List<decimal>> list= new List<List<decimal>>();
list.Add(new List<decimal>(){ 1.501M,2.231M,3M});
list.Add(new List<decimal>(){ 4.505M,5M,3M});
list.Add(new List<decimal>(){ 1M,7M,8M});
var result = list.Select(x=>x.Select(y=>Math.Round(y,2)).ToList()).ToList();
foreach(var a in result)
{
    foreach(var b in a)
    {
        Console.Write(b + "\t");
    }
    Console.WriteLine();
}

      

+1


source







All Articles