将两个小数列表值相乘 [英] Multiply two decimal list values

查看:60
本文介绍了将两个小数列表值相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有listA,listB包含相同的数量



列表< decimal> listA =  new 列表< decimal>(){ 1  .5M, 2  .63M, 1  .25M}; 

List< decimal> listB = new 列表< decimal>(){ 2 .5M,0M,1M};





i需要乘法列表A * listB表示



  1  .5M * 2.5M =  3  .75M 
2 .63M * 0M = OM
1 .25M * 1M = 1 .25M





如上所述我需要另一份清单C

怎么办请帮助。



i尝试使用 listA [0] * listB [0];

是这个正确,但我在运行时更改了计数

解决方案

  //  < span class =code-comment>使用Linq  
使用 Linq

List< decimal> listA = new 列表< decimal>(){ 1 .5M, 2 .63M, 1 .25M};

List< decimal> listB = new 列表< decimal>(){ 2 .5M,0M,1M};

List< decimal> listC = listA.Select((dValue,index)= > dValue * listB [index])。ToList();



这使用Linq'Select的形式自动为您创建索引[ ^ ]。



请注意,如果ListA的元素多于ListB,则会失败,但如果ListA的元素少于ListB,则可以正常工作。您可能希望在代码中进行测试以确保两个列表具有相同数量的元素?


这个怎么样:

  var  listC =  new 列表< decimal>(listA.Zip(listB,(a,b)=> a * b)) ; 

干杯

Andi


通过循环实现此实现的一种简单方法。

你必须首先进行一些验证,检查你的输入列表是否具有相同的长度,或者如果没有决定在这些情况下做什么的规则。

例如:

  //  选择两个最短的列表 
// 我假设您的列表中有一个Count属性。
// (正如谢尔盖指出的那样,列表类型未定义)
int length =(listA.Count > listB.Count)? listB.Count:listA.Count;



在此之后创建listC并遍历列表项是一件简单的事情,将它们相乘并将它们放在listC中。


i have listA,listB Contains same count

List<decimal> listA =new List<decimal>(){1.5M,2.63M,1.25M};

List<decimal> listB =new List<decimal>(){2.5M,0M,1M};



i need multiply listA*listB means

1.5M*2.5M=3.75M
2.63M*0M=OM
1.25M*1M=1.25M



like above i need another List listC
how to do it please help.

i tried with listA[0]*listB[0];
is this correct but i have changed count at runtime

解决方案

// uses Linq
using Linq

List<decimal> listA = new List<decimal>() { 1.5M, 2.63M, 1.25M };

List<decimal> listB = new List<decimal>() { 2.5M, 0M, 1M };

List<decimal> listC = listA.Select((dValue, index) => dValue * listB[index]).ToList();


This uses the form of Linq 'Select which automatically creates an index for you [^].

Note that this would fail if ListA had more elements than ListB, but work if ListA had fewer elements than ListB. You may want to put a test in your code to ensure both lists have the same number of elements ?


How about this:

var listC = new List<decimal>(listA.Zip(listB,(a,b)=>a*b));

Cheers
Andi


One straightforward way to do this implementation is via a loop.
You have to do some validation first to check that both your input lists are of the same length, or if not decide rules for what to do in these cases.
For example:

// Choose the shortest list of the two
// I am assuming here that your list has a Count property. 
// (As Sergey pointed out, the type of list is undefined)
int length = (listA.Count > listB.Count) ? listB.Count : listA.Count;


After this it is a simple matter to create listC and loop through the list items, multiply them and put them in listC.


这篇关于将两个小数列表值相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆