What is the purpose of “!” and “?” at the end of method names?

It’s “just sugarcoating” for readability, but they do have common meanings: Methods ending in ! perform some permanent or potentially dangerous change; for example: Enumerable#sort returns a sorted version of the object while Enumerable#sort! sorts it in place. In Rails, ActiveRecord::Base#save returns false if saving failed, while ActiveRecord::Base#save! raises an exception. Kernel::exit causes a script … Read more

How to wait until a predicate condition becomes true in JavaScript?

Javascript is single threaded, hence the page blocking behaviour. You can use the deferred/promise approach suggested by others. The most basic way would be to use window.setTimeout. E.g. function checkFlag() { if(flag === false) { window.setTimeout(checkFlag, 100); /* this checks the flag every 100 milliseconds*/ } else { /* do something*/ } } checkFlag(); Here … Read more

Delegates: Predicate vs. Action vs. Func

Predicate: essentially Func<T, bool>; asks the question “does the specified argument satisfy the condition represented by the delegate?” Used in things like List.FindAll. Action: Perform an action given the arguments. Very general purpose. Not used much in LINQ as it implies side-effects, basically. Func: Used extensively in LINQ, usually to transform the argument, e.g. by … Read more

How to convert a String to its equivalent LINQ Expression Tree?

Would the dynamic linq library help here? In particular, I’m thinking as a Where clause. If necessary, put it inside a list/array just to call .Where(string) on it! i.e. var people = new List<Person> { person }; int match = people.Where(filter).Any(); If not, writing a parser (using Expression under the hood) isn’t hugely taxing – … Read more

Why Func instead of Predicate?

While Predicate has been introduced at the same time that List<T> and Array<T>, in .net 2.0, the different Func and Action variants come from .net 3.5. So those Func predicates are used mainly for consistency in the LINQ operators. As of .net 3.5, about using Func<T> and Action<T> the guideline states: Do use the new … Read more

Find first element in a sequence that matches a predicate [duplicate]

To find the first element in a sequence seq that matches a predicate: next(x for x in seq if predicate(x)) Or simply: Python 2: next(itertools.ifilter(predicate, seq)) Python 3: next(filter(predicate, seq)) These will raise a StopIteration exception if the predicate does not match for any element. To return None if there is no such element: next((x … Read more