score:11
What you want is a combination of Aggregate and TakeWhile, so let's write that.
public static IEnumerable<S> AggregatingTakeWhile<S, A>(
this IEnumerable<S> items,
A initial,
Func<A, S, A> accumulator,
Func<A, S, bool> predicate)
{
A current = initial;
foreach(S item in items)
{
current = accumulator(current, item);
if (!predicate(current, item))
break;
yield return item;
}
}
And so now you can say
var items = myObjList.AggregatingTakeWhile(
0,
(a, s) => a + s.MyValue,
(a, s) => a <= 5);
Note that I have made the decision here to consult the predicate after the accumulator has been updated; depending on your application, you might want to tweak that slightly.
Another solution would be to combine aggregation with enumeration:
public static IEnumerable<(A, S)> RunningAggregate<S, A>(
this IEnumerable<S> items,
A initial,
Func<A, S, A> accumulator)
{
A current = initial;
foreach(S item in items)
{
current = accumulator(current, item);
yield return (current, item);
}
}
And now your desired operation is
var result = myObjList
.RunningAggregate(0, (a, s) => a + s.MyValue)
.TakeWhile( ((a, s)) => a <= 5)
.Select(((a, s)) => s);
I might have gotten the tuple syntax wrong there; I haven't got Visual Studio handy right now. But you get the idea. The aggregation produces a sequence of (sum, item) tuples, and now we can use normal sequence operators on that thing.
score:5
For an old-school, non-Linq approach, you could write a simple method for this:
static List<MyObj> GetItemsUntilSumEquals(List<MyObj> items, int maxSum)
{
if (items == null) return null;
var result = new List<MyObj>();
var sum = 0;
foreach (var item in items)
{
if (sum + item.MyValue > maxSum) break;
sum += item.MyValue;
result.Add(item);
}
return result;
}
Source: stackoverflow.com
Related Articles
- How to get subset of List<T> items based on their Sum of an object property
- Create a subset of an object based off an array of property names
- Linq Distinct based on property of object
- Use Linq to filter Hashtable based on a property of Values custom object
- Using LINQ to get the difference between two list of objects based only on a single object property
- How can I use Distinct on a specific property and select the object to keep based on a predicate?
- Merge items of list based on common property
- Select items in one object where a property is in a list<string>
- Apply PredicateBuilder to query a single object property of a list of items
- Property containing subset of related object
- LINQ: Compare two list based on their properties and return items that match certain conditions
- Sorting Array based on property of object on inner array
- How to write a lambda to get one property based on another property in an object
- Extract objects from a nested object based on a property value and project to a new class
- How to filter an object list based on an unknown property
- Finding Duplicates based On A Property In Object
- Removing Items from a list of objects when an object property is duplicated
- Ordering map based on property in list of object
- Linq: Select object based on property
- How can I group items in an object if a property is the same?
- LINQ Select Object based on a property within a list within the object
- Return items in one list based upon their matching index in another using Linq
- Excluding items from a list by object property
- Linq how to filter an object list based on overlap of nested list property and external list
- Linq select array items based on sub class property
- c# rearranging class object based on property values?
- Find subset in List of objects based on matched property in string array
- Howto add a subset of a List to a property of an object in another List - best/fastest practice
- Linq results based on a property of an object in a inner list
- Linq how to query a list of items for a combined list of a child collection based on a property of the parent item
- Remove a condition from an expression using an ExpressionVisitor
- Linq join get null rows filter with where
- Converting DataTable to XML using XElement as template
- Remove empty entries from list of list of strings
- How do I exclude a member from Linq-To-Sql mapping?
- LINQ (C#) Sum a String in a HH:mm format
- How to write LINQ query row numbers in C#?
- Alternative to walking arrays of arrays in NUnit?
- LINQ Select()/Any() misbehaving?
- Linq to join two tables using a value to where clause dynamically
- Will the condition on a LINQ Where-statement re-evaluate during the loop?
- Why is C# console application not returning result on LINQ Select with data
- LINQ to SQL sum null value
- Group Products by Brand then by Category - linq
- linq groupby without time field vb.net
- Making expressions from lambda functions that are not for comparison
- Combining two tables into one
- Why is dataContext.GetChangeSet().Deletes.Count() always returning 0?
- how to execute custom function for each item later using linq deferred execution?
- Return Dictionary<int,List<Int>> from EntityFramework table