更新时间:2022-12-20 11:40:18
您可以使用简单的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