LINQ是否可以获取元组值并将其汇总等到新元组中? [英] LINQ for grabbing Tuple values and aggregating, etc. into new tuple?

查看:91
本文介绍了LINQ是否可以获取元组值并将其汇总等到新元组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个小问题,因为我将我的元组重构为一个新的元组,在重构所有项目时我很害怕,所以我想添加到我的新元组中:不是b的总和,然后是b的总和重复直到列表结束,问题是,我不想使用循环,但是现在我很谦虚,而且我愿意接受循环建议,但是仍然可以使用linq的方法更轻松地进行此操作吗?我听说聚合可能是我可以使用的东西 示例代码:

Got a small problem, as im refactoring my tuple into a new tuple, im getting scared when refactoring all the items, i want to add to my new tuple: sum of what's not 'b', then 'b', then repeat till the list ends, problem is, i dont want to use loops but now I'm humbled and I am open to loop recommendations, but still, is there a linq way to do this easier? and I hear aggregate is something I can use perhaps example code:

var newList = new List<Tuple<char, decimal>>();

newList.Add(new Tuple<char, decimal>('q', .3M));
newList.Add(new Tuple<char, decimal>('w', .4M));
//.7
newList.Add(new Tuple<char, decimal>('b', 1.2M));
//1.2
newList.Add(new Tuple<char, decimal>('r', .3M));
newList.Add(new Tuple<char, decimal>('e', .8M));
//1.1
newList.Add(new Tuple<char, decimal>('b', 1.2M));
//1.2
newList.Add(new Tuple<char, decimal>('b', 1.2M));
//1.2
newList.Add(new Tuple<char, decimal>('b', 1.2M));
//1.2

var refactoredList = new List<Tuple<char, decimal>>();

refactoredList.Add(
    new Tuple<char, decimal>(
        's', 
        newList.TakeWhile(x => x.Item1 != 'b').Sum(x => x.Item2)));
refactoredList.Add(
    new Tuple<char, decimal>(
        'b', 
        newList.Where(x => x.Item1 == 'b').Select(x => x.Item2).First()));

推荐答案

不确定您在做什么.看起来您正在获取连续的b和非b值的总和.写一个生成器.

Not sure what exactly you're doing. Looks like you're getting the sum of consecutive b and non-b values. Write a generator.

IEnumerable<Tuple<char, decimal>> AggregateGroups(IEnumerable<Tuple<char, decimal>> data)
{
    var state = default(char?);
    var sum = 0M;
    foreach (var item in data)
    {
        if (state != null && state.Value == 'b' ^ item.Item1 == 'b')
        {
            yield return Tuple.Create(state.Value, sum);
            sum = 0M;
        }
        state = item.Item1 == 'b' ? 'b' : 's';
        sum += item.Item2;
    }
    if (state != null)
        yield return Tuple.Create(state.Value, sum);
}

然后使用它:

var data = new[]
{
    Tuple.Create('q', .3M),
    Tuple.Create('w', .4M),
    //.7
    Tuple.Create('b', 1.2M),
    //1.2
    Tuple.Create('r', .3M),
    Tuple.Create('e', .8M),
    //1.1
    Tuple.Create('b', 1.2M),
    //1.2
    Tuple.Create('b', 1.2M),
    //1.2
    Tuple.Create('b', 1.2M),
};
var result = AggregateGroups(data).ToList();

这将显示在列表中:

(s, 0.7)
(b, 1.2)
(s, 1.1)
(b, 3.6)

这篇关于LINQ是否可以获取元组值并将其汇总等到新元组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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