-3

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!!!

Sainath
  • 19
  • 7
  • ‘Items.Select(a=>a/10)’ with linq, no idea about performance – Lucian Bumb Jun 29 '22 at 04:24
  • Does this answer your question? [Update all objects in a collection using LINQ](https://stackoverflow.com/questions/398871/update-all-objects-in-a-collection-using-linq) – Ibrennan208 Jun 29 '22 at 04:27
  • Or `var resArray = Array.ConvertAll([Source Array], (v)=> (v* percent) / 100);` – Jimi Jun 29 '22 at 04:31
  • What trouble are you having finding the appropriate LINQ method? If you're not already familiar with what method(s) to use then start with the iterative approach — it can't be more than 5 lines of code — and use that to figure out what building blocks of LINQ you need to assemble together. – Lance U. Matthews Jun 29 '22 at 04:40
  • Thanks!!! for the response. The issue is if there are values like '999', % should not be calculated on such items, but those items (value = 999) also should be copied to new array at the same index. In Linq, if we put where condition then all the items with 999 will get excluded. So, trying to avoid looping. – Sainath Jun 29 '22 at 07:49

1 Answers1

0

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 / percentage).ToArray();

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

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
Francesco D.M.
  • 2,129
  • 20
  • 27
  • Thanks a lot!!! It is working as expected. Apologies. I have updated the question. Actually 999 values should be retained as it is. – Sainath Jun 29 '22 at 09:08
  • Note that the `ToArray()` method will force the calculation of all values as it will enumerate the whole collection. If you do not necessarily need this you might be better off by not calling it and passing around the `IEnumerable` returned by the `Select` method. – Francesco D.M. Jun 29 '22 at 09:20