2

I have 2 lists:

  1. List<int> listOne say [1,2,3,4]
  2. List<int> listTwo say [111,222,333,444]

Now I want to make a resultant List<int> using the above 2 lists, making some calculation like [1*100/111, 2*100/222 ,... listOne[i]*100/listTwo[i].,...]

What I have tried:

resultantList = listOne.Select((s, i) => new { s * 100 / listTwo[i] }).ToList();

resultantList = listOne.Select((s, i) => s * 100 / listTwo[i]).ToList();

But this doesn't compile. How should I frame the LINQ for this?

jAntoni
  • 591
  • 1
  • 12
  • 28
  • 3
    Your second one should compile fine. Zip (as in DavidG's answer) is better but your second option should have worked perfectly fine. What compile error did you have with it? – Chris Aug 14 '17 at 11:09
  • 1
    here is a `zip` sample for your question.[link](https://stackoverflow.com/a/5122785/2332844) – Badiparmagi Aug 14 '17 at 11:10
  • Yes, its compiling, just checked again patiently now. Thanks lot I remember It was showing error like 'Anonymous member declarator ...' Actually this deals with realtime data to be displayed on the Dashboard. Which is best way to go about? I see many answers here. Is LINQ & mine calculates\performs faster. This list is one of the value (inside an object) that needs to keep changing on page as per the data received back-end. Please advice. – jAntoni Aug 14 '17 at 11:31

4 Answers4

5

You can use Linq Zip, for example:

var results = listOne.Zip(listTwo, 
    (one, two) => one*100 / (decimal)two);

Note: the cast to decimal is important otherwise the division will produce integer output (which is always zero in your test data)

DavidG
  • 113,891
  • 12
  • 217
  • 223
2

You can use Zip

List<int> result = listOne.Zip(listTwo, (i1, i2) => i1 * 100 / i2).ToList();

But because of integer division i expect all values to be 0 because even multiplied with 100 the division result is less than 1. So maybe you want to use decimal:

List<decimal> result = listOne.Zip(listTwo, (i1, i2) => decimal.Divide(i1 * 100, i2)).ToList();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1
var resultList = new List<int>();
for(var i = 0; i < listOne.Count; i++)
{
  resultList.Add((listOne[i] * 100) / (decimal)listTwo[i]);
}
Ivan Mladenov
  • 1,787
  • 12
  • 16
0

The operation mathematical operation is done using select statement and stored in resultant list.The result will be a decimal number hence the output list is a decimal list.The inputs are typecasted to decimal to perform the operation

List<decimal> result = listOne.Select((x,i) => (decimal)x*100 / (decimal)listTwo[i]).ToList();

TripVik
  • 47
  • 8