C
C#ā€¢2y ago
PatrickG

ā” want to add a conditional .Take(10) to a query without duplicating the code

Im looking for an easy way to add a .Take(10) or .Take(x) to a iqueryable so that my test go faster instead of running on the entire data. is there a way to make it so if x is null it takes all or ignres the take() option ??
14 Replies
Head0nF1re
Head0nF1reā€¢2y ago
"so that my test go faster instead of running on the entire data". What do you mean?
PatrickG
PatrickGOPā€¢2y ago
well lets say my code is context.Customers.Tolist().Foreach( DO A LOT OF STUFF ) I would like to add a .Take(10) but only if i passed an argument that says to run this in test i could do if (isTest){ context.Customers.Take(10).Tolist().Foreach( DO A LOT OF STUFF ) } else{ context.Customers.Tolist().Foreach( DO A LOT OF STUFF ) } but i have to change tons of queries of this kind so I was wondering if theres a way to put the Take() and basically takeAll unless otherwise specified
Pobiega
Pobiegaā€¢2y ago
public static IQueryable<T> AllOrSome<T>(this IQueryable<T> queryable, int? take = null)
=> take is not null
? queryable.Take(take.Value)
: queryable;
public static IQueryable<T> AllOrSome<T>(this IQueryable<T> queryable, int? take = null)
=> take is not null
? queryable.Take(take.Value)
: queryable;
PatrickG
PatrickGOPā€¢2y ago
ok so its not builtin
Pobiega
Pobiegaā€¢2y ago
no, ofc not its a bit weird šŸ˜›
Head0nF1re
Head0nF1reā€¢2y ago
Do ToList() after the ifs, just to see what happens Also, weird requirement that "test" thing
PatrickG
PatrickGOPā€¢2y ago
the thing is i dont want a if lol
Pobiega
Pobiegaā€¢2y ago
so use the extension method provided above but its a bit weird. in general your approach should be that tests provide their own data
PatrickG
PatrickGOPā€¢2y ago
yea that's basically what I wanted but I thought there might have been something of this kind already existing in LINQ
Head0nF1re
Head0nF1reā€¢2y ago
It's just for you to understand what happens. Since in your example you did multiple ToList(), I don't think you understand what fundamentally happens
PatrickG
PatrickGOPā€¢2y ago
its ok dont worry about it its not a format unit test, im just gonna change it to 'test mode' and run it to see something
Pobiega
Pobiegaā€¢2y ago
i see
PatrickG
PatrickGOPā€¢2y ago
formal*
Accord
Accordā€¢2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server