LINQ用于获取元组值和聚合等等到新元组?

时间:2016-04-20 23:24:14

标签: c# linq

有一个小问题,因为我将我的元组重构成一个新元组,我在重构所有项目时感到害怕,我想添加到我的新元组:什么不是' b&#的总和39;然后' b',然后重复直到列表结束,问题是,我不想使用循环,但现在我很谦卑,我愿意循环推荐,但是,仍然,是一个linq的方式来做到这一点更容易?我听说聚合是我可以使用的东西 示例代码:

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()));

2 个答案:

答案 0 :(得分:0)

我不确定你的意思,但这里有一个示例代码,可以为您提供两组元组

        var sumOfB = newList
            .GroupBy(x => x.Item1)
            .Where(g => g.Key == 'b')
            .Select(s => Tuple.Create('b', s.Sum(t=> t.Item2)));

        var sumOfNotB = newList
            .GroupBy(x => x.Item1)
            .Where(g => g.Key != 'b')
            .Select(s => Tuple.Create('s', s.Sum(t => t.Item2)));

LinqPad Result

答案 1 :(得分:0)

不确定你到底做了什么。您似乎已获得连续b和非b值的总和。写一个发电机。

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)