c# - 如何根据运行总计在 Linq 中分组和/或选择

标签 c# linq linq-to-objects

我有一个要求,我需要对运行量超过阈值 10 的交易进行分组和选择。一旦超过阈值,运行计数将被重置。

这是我正在尝试做的一个例子......

以下是一些交易:

Id | Amount
1  | 5.50
2  | 4.10
3  | 1.20
4  | 1.05
5  | 3.25
6  | 1.25
7  | 5.15
8  | 8.15
9  | 5.15

我想达到的结果是:

第 1 组:

Id | Amount
1  | 5.50
2  | 4.10    
3  | 1.20

第 2 组:

4  | 1.05
5  | 3.25    
6  | 1.25   
7  | 5.15  

第 3 组:

8  | 8.15
9  | 5.15

我提出了一个使用 for 循环和 yield 的解决方案。你可以在https://dotnetfiddle.net/rcSJO4上看到它以及下面的内容。

我只是想知道是否有更优雅的解决方案,以及是否有可以使用 Linq 实现的更聪明且更易读的方法。

我的解决方案:

using System;
using System.Linq;
using System.Collections.Generic;

public class Transaction{
    public int Id { get; set;}
    public decimal Amount { get; set;}        
}


public class Program
{
    public static void Main()
    {

        var transactions = new Transaction [] { 
            new Transaction {Id = 1, Amount = 5.50m},
            new Transaction {Id = 2, Amount = 4.10m},
            new Transaction {Id = 3, Amount = 1.20m},
            new Transaction {Id = 4, Amount = 1.05m},
            new Transaction {Id = 5, Amount = 3.25m},
            new Transaction {Id = 6, Amount = 1.25m},
            new Transaction {Id = 7, Amount = 5.15m},
            new Transaction {Id = 8, Amount = 8.15m},
            new Transaction {Id = 9, Amount = 5.15m},
        };

        var grouped = ApplyGrouping(transactions);

        foreach(var g in grouped)
        {
            Console.WriteLine("Total:" + g.Item1);

            foreach(var t in g.Item2){
                Console.WriteLine(" " +t.Amount);
            }
            Console.WriteLine("---------");
        }

    }

    private static IEnumerable<Tuple<decimal, IEnumerable<Transaction>>> ApplyGrouping(IEnumerable<Transaction> transactions){

        decimal runningTotal = 0m;
        decimal threshold = 10m;

        var grouped = new List<Transaction>();

        foreach(var t in transactions){

            grouped.Add(t);
            runningTotal += t.Amount;

            if (runningTotal <= threshold) continue;

            yield return new Tuple<decimal, IEnumerable<Transaction>>(runningTotal, grouped);

            grouped.Clear();
            runningTotal = 0;
        }

    }
}

最佳答案

我不知道您是否会找到一个完全令人满意的解决方案。没有内置的 Linq 运算符(或运算符组合)会以美观的方式执行此操作。您的方法 - 将复杂性重构为扩展方法 - 是最好的方法。没有什么不妥。无论如何,这就是 Linq 的全部内容;只是一个隐藏杂乱位的抽象。但是,如果您发现自己经常使用这种模式,我会说您可以将代码重构为更通用的代码。您现在所拥有的只会在这种非常特殊的情况下起作用。如果你这样做:

public static class EnumerableExtensions
{
    public static IEnumerable<TResult> GroupUntil<TSource, TAccumulation, TResult>(
        this IEnumerable<TSource> source,
        Func<TAccumulation> seedFactory,
        Func<TAccumulation, TSource, TAccumulation> accumulator,
        Func<TAccumulation, bool> predicate,
        Func<TAccumulation, IEnumerable<TSource>, TResult> selector)
    {
        TAccumulation accumulation = seedFactory();
        List<TSource> result = new List<TSource>();
        using(IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            while(enumerator.MoveNext())
            {
                result.Add(enumerator.Current);
                accumulation = accumulator(accumulation, enumerator.Current);
                if(predicate(accumulation))
                {
                    yield return selector(accumulation, result);
                    accumulation = seedFactory();
                    result = new List<TSource>();
                }
            }

            if(result.Count > 0)
            {
                yield return selector(accumulation, result);
            }
        }
    }
}

然后,对于你的情况,你可以这样调用它:

var grouped = 
    transactions
    .GroupUntil(
        () => 0.0m,
        (accumulation, transaction) => accumulation + transaction.Amount,
        (accumulation) => accumulation > 10.0m,
        (accumulation, group) => new { Total = accumulation, Transactions = group})

但它足够通用,可以在其他地方使用。

关于c# - 如何根据运行总计在 Linq 中分组和/或选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906652/

相关文章:

c# - 多 channel GroupBy() 如何比单 channel 更快?

c# - 如何在 MVVM Light SimpleIoc 中注册一系列依赖项

c# - 生成字符串列表的所有组合

c# - 如何使用 lambda 表达式或使用任何其他逻辑转换数据?

c# - LINQ - 根据类型获取子集

c# - 如何在返回集合的 lambda 中使用异步

c# - 这两个 linq 实现有什么区别?

c# - 最近用户查询

c# - 在 C# 中使用 abcpdf 从 PDF A/3 中提取嵌入的 XML 文件 - ZUGFeRD

c# - 如何使用 SharpSSH 将文件移动到 SFTP 服务器