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 Query
- How to get subset of List<T> items based on their Sum of an object property
- How to write a lambda to get one property based on another property in an object
- How to get an object from a list based upon IEqualityComparer<T>
- Create a subset of an object based off an array of property names
- 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?
- How do I get the maximum object of a group by criteria (the entire object, not a property of it)
- How to get the sum of the volume of highest and lowest priced items in linq
- How to get Sum from List in another List as a property with linq
- How to the get an object based on 2 criteria without doing extensive searching?
- How to get intersection of two classes based on property
- how to find items in list that their sum is less than or equal a number
- How to get specific items from List<object> when all the object are different types of EventArgs
- How to get difference sum of between keys in a Dictionary object C#
- How to get the property from a list of object that is a string with the lowest numeric value
- How to get property value from .net dynamic array object
- How to filter an object list based on an unknown property
- How can I get a SUM of the items in my grouped query?
- How do I get list of object property names and values in C#?
- How can I group items in an object if a property is the same?
- Linq how to filter an object list based on overlap of nested list property and external list
- How can I get more than one property from an object list to an array?
- How to get the Sum of specific property using dynamic query
- How to get items of an entity's collection property using Linq?
- Linq how to query a list of items for a combined list of a child collection based on a property of the parent item
- How to set an Id property using linq based on the id set in a preceding object in EF DbInitializer
- How to get common object from a list of object based on a property?
- How to use LINQ to select object with minimum or maximum property value
- How to perform .Max() on a property of all objects in a collection and return the object with maximum value
- How can I get LINQ to return the object which has the max value for a given property?
More Query from same tag
- LINQ query not working properly
- LINQ: How Can I Use Equals in query
- Group by date-part (dd.mm.yyyy)
- Entity Framework Code First without app.config
- Linq query reporting 'invalid column name' on computed column in EF4.2
- LINQ to Entities does not recognize the method 'System.TimeSpan Subtract(System.DateTime)' method
- C# Is it possible to abstract an orderby LINQ clause into a function parameter?
- Join multiple list on property in parallel
- Change this Loop by LINQ?
- VB.Net LINQ - left outer join between two datatables - limit to one row
- List from nested Values XML Linq C#
- Is there a neater linq way to 'Union' a single item?
- Populate dictionary from enum
- Split a list based on another list c#
- How to change values of few properties from one list to another using LINQ C#:
- How to get the value by a key from a super nested Json
- The result of a query cannot be enumerated more than once
- Changing variable in LINQ select
- Queryable variable cannot be found in the context
- Filter datatable by multiple statements
- Is it important to define both ends of relationships/FKs with Entity Framework?
- How to manipulate results from linq
- Saving read only database table in local variable during program execution
- BindingSource doesn't appear to contain Properties created in partial class
- Question about a terminology which implements something like this list.Add(new{a=1, b=2})
- Could not determine metatable error binding list to asp.net datagridview
- Filtering object containing objects from another table using linq c#
- LINQ for getting all entries of a IEnumerable<string> which start with the same characters
- C# Linq - Delayed Execution
- Unable to cast object of type 'WhereEnumerableIterator`1' to type 'System.Collections.Generic.ICollection`1