有条件地对元组列表中的值求和 [英] Conditionally sum values in a list of tuples

查看:80
本文介绍了有条件地对元组列表中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想做的很简单,我有一个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扩展名, 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

这篇关于有条件地对元组列表中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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