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.

Did you find this page helpful?