LINQ, simplifying expression - take while sum of taken does not exceed given value

前端 未结 5 1202
别那么骄傲
别那么骄傲 2021-01-04 03:50

Given a setup like this ..

class Product {
   int Cost;
   // other properties unimportant
}

var products = new List {
    new Product { Cost         


        
5条回答
  •  萌比男神i
    2021-01-04 04:08

    Others have pointed out the captured variable approach, and there are arguably correct viewpoints that this approach is bad because it mutates state. Additionally, the captured variable approaches can only be iterated once, and are dangerous because a. you might forget that fact and try to iterate twice; b. the captured variable does not reflect the sum of the items taken.

    To avoid these problems, just create an extension method:

    public static IEnumerable TakeWhileAggregate(
        this IEnumerable source,
        TAccumulate seed,
        Func func,
        Func predicate
    ) {
        TAccumulate accumulator = seed;
        foreach (TSource item in source) {
            accumulator = func(accumulator, item);
            if (predicate(accumulator)) {
                yield return item;
            }
            else {
                yield break;
            }
        }
    }
    

    Usage:

    var taken = products.TakeWhileAggregate(
        0, 
        (cost, product) => cost + product.Cost,
        cost => cost <= credit
    );
    

    Note that NOW you can iterate twice (although be careful if your TAccumulate is mutable a reference type).

提交回复
热议问题