0

Is is possible to assign an array of decimal values to a list of integers? Let's say I have an array like decimal[] decemalNumbers and a list of integers like List intNumbers. So can I do the assignment like intNumbers = decemalNumbers.ToList()?

How Can I do an explicit conversion? Is it possible?

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
Ash18
  • 121
  • 3
  • 12

2 Answers2

2

A simple LINQ solution:

decimal[] decimalNumbers = {1.11m,5.22m,3.25m,4.66m,9.13m};
List<int> integerNumbers = decimalNumbers.Select(x => Convert.ToInt32(x)).ToList();

Output:

integerNumbers[0]=1
integerNumbers[1]=5
integerNumbers[2]=3
integerNumbers[3]=5
integerNumbers[4]=9
Slaven Tojić
  • 2,945
  • 2
  • 14
  • 33
0

try like this , to convert it to int

// obj is decimal array or list
IEnumerable<int> result = obj.select(d=> decimal.ToInt32(d));
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 1
    Using `Cast` on decimal[] will result in an InvalidCastException when you start iterating. You have to use an explicit cast such as in `Select(d => (int)d)`. For an explanation why Cast does not work see [this answer](https://stackoverflow.com/questions/445471/puzzling-enumerable-cast-invalidcastexception). – Mike Zboray Mar 12 '18 at 06:18
  • @mikez - let me try at my end ...because cast is ment for casing value – Pranay Rana Mar 12 '18 at 06:19
  • @PranayRana `Cast` first boxes the value to `object`, before casting it, which then causes the `InvalidCastException`. – Dirk Mar 12 '18 at 06:25