有条件地对元组列表中的值求和

编程入门 行业动态 更新时间:2024-10-08 07:25:48
本文介绍了有条件地对元组列表中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

您好,我想做的很简单,我有一个List<tuple>(string, decimal),如果有两个相似的字符串,我想获取十进制值的总和.

Hello what I'm trying to do is hopefully simple, I have a List<tuple>(string, decimal) and I'm trying to grab the sum of the decimal values if there are two similar strings.

我的列表包含以下值:

  • ("q",.5)
  • ("w",1.5)
  • ("e",.7)
  • ("r",.8)
  • ("q",.5)

因此,所有值的总和为.5 + 1.5 + .7 + .8 + .5 = 4.0.

The sum of all the values would therefore be .5 + 1.5 + .7 + .8 + .5 = 4.0.

我认为算法将是这样的:

I assume the algorithm would be something like this:

newlist.select(item1 , item2).where(get the sum of first "q" up to the next "q" in list)

对于现有代码,我不仅只有列表的声明及其值.

As for existing code, I don't have much only the declaration of the list and it's values.

**我想要'q'和'q'之间的总和+'q'和'q'的值,而不仅仅是中间值,答案应该是'4'而不是3,我希望所有之间q和q包括q的值,谢谢.

**I want the sum between 'q' and 'q' + the values of 'q' and 'q', not just in-between, the answer should be '4' and not 3, I want everything between q and q including q's values, thank you.

推荐答案

您可以使用简单的Linq扩展名, SkipWhile 和 TakeWhile

You could use simple Linq extensions, SkipWhile and TakeWhile

List<Tuple<string,double>> items = new List<Tuple<string,double>>() { new Tuple<string,double>("q", .5), new Tuple<string,double>("w", 1.5), new Tuple<string,double>("e", .7), new Tuple<string,double>("r", .8), new Tuple<string,double>("q", .5) }; var sumvalue = items.Sum(c=>c.Item2); // Calculates sum of all values var betweensum = items.SkipWhile(x=>x.Item1 == "q") // Skip until matching item1 .TakeWhile(x=>x.Item1 != "q") // take until matching item1 .Sum(x=>x.Item2); // Sum

按照评论中的要求,如果您有多个这样的集合,并且想要在多个集合的匹配字符串之间进行计数,请执行此操作.

As asked in the comments, in case if you have multiple such sets and you want count in between those matching strings for multiple sets, do this.

int gid = 0; items.Select(c => new { Tuple = c, gid = c.Item1=="q"? ++gid : gid }) .GroupBy(x=>x.gid) .Where(x=>x.Key%2==1) .SelectMany(x=>x.Skip(1)) .Sum(x=>x.Tuple.Item2);

工作 Demo

更多推荐

有条件地对元组列表中的值求和

本文发布于:2023-11-30 07:44:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!