jAntoni
jAntoni

Reputation: 621

LINQ C# Calculating a List value using 2 lists

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?

Upvotes: 2

Views: 1207

Answers (4)

TripVik
TripVik

Reputation: 47

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();

Upvotes: 0

Ivan Mladenov
Ivan Mladenov

Reputation: 1847

var resultList = new List<int>();
for(var i = 0; i < listOne.Count; i++)
{
  resultList.Add((listOne[i] * 100) / (decimal)listTwo[i]);
}

Upvotes: 1

DavidG
DavidG

Reputation: 119017

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)

Upvotes: 5

Tim Schmelter
Tim Schmelter

Reputation: 460208

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();

Upvotes: 2

Related Questions