簡體   English   中英

LINQ是否可以獲取元組值並將其匯總等到新元組中?

[英]LINQ for grabbing Tuple values and aggregating, etc. into new tuple?

有一個小問題,因為我將我的元組重構為一個新的元組,在重構所有項目時我很害怕,所以我想添加到我的新元組中:不是'b'的總和,然后是'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()));

我不確定您的意思,但是下面的示例代碼為您提供了兩組元組

        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結果

不知道你到底在做什么。 看起來您正在獲取連續的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM