Home > Software design >  Calculate % of each item of an array in C#
Calculate % of each item of an array in C#

Time:06-30

We have an api that returns an array with lot of integer values (more than 10k items within array). Need to calculate % value of each item in array and return new array.

Ex:

"Array": [ 600, 100, 300, 400, 999, 50, 0, 0, 10,.....]
"Percentage": 10

Newarray = [60,10,30,40, 999, 5, 0, 0 , 1....]

Looking for a simple way to return an array using Linq or Lambda expression instead of looping through each item of array using Foreach.

Thanks!!!

CodePudding user response:

I'm not sure I understand the 999 value thing you mentioned (in the comments you say the percentage should not be calculated but in your example you did calculate it) but this code should either give you the solution or at least give you enough information to solve your issue.

var percentage = 10;
var firstArray = new int[] {600, 100, 999, 50, 0};
var resultArray = firstArray.Select(x => x == 999 ? x : x / 10).ToArray();

For this you need to import Linq: using System.Linq;

  • Related