C#: Getting Names of properties in a chain from lambda expression

Something like this? public void Foo<T, P>(Expression<Func<T, P>> expr) { MemberExpression me; switch (expr.Body.NodeType) { case ExpressionType.Convert: case ExpressionType.ConvertChecked: var ue = expr.Body as UnaryExpression; me = ((ue != null) ? ue.Operand : null) as MemberExpression; break; default: me = expr.Body as MemberExpression; break; } while (me != null) { string propertyName = me.Member.Name; Type … Read more

How to use await in a python lambda

You can’t. There is no async lambda, and even if there were, you coudln’t pass it in as key function to list.sort(), since a key function will be called as a synchronous function and not awaited. An easy work-around is to annotate your list yourself: mylist_annotated = [(await some_function(x), x) for x in mylist] mylist_annotated.sort() … Read more

LINQ identity function

Unless I misunderstand the question, the following seems to work fine for me in C# 4: public static class Defines { public static T Identity<T>(T pValue) { return pValue; } … You can then do the following in your example: var result = enumerableOfEnumerables .SelectMany(Defines.Identity); As well as use Defines.Identity anywhere you would use a … Read more

Implement recursive lambda function using Java 8

I usually use (once-for-all-functional-interfaces defined) generic helper class which wraps the variable of the functional interface type. This approach solves the problem with the local variable initialization and allows the code to look more clearly. In case of this question the code will look as follows: // Recursive.java // @param <I> – Functional Interface Type … Read more

Java 8 optional: ifPresent return object orElseThrow exception

Actually what you are searching is: Optional.map. Your code would then look like: object.map(o -> “result” /* or your function */) .orElseThrow(MyCustomException::new); I would rather omit passing the Optional if you can. In the end you gain nothing using an Optional here. A slightly other variant: public String getString(Object yourObject) { if (Objects.isNull(yourObject)) { // … Read more

Proper way to receive a lambda as parameter by reference

You cannot have an auto parameter. You basically have two options: Option #1: Use std::function as you have shown. Option #2: Use a template parameter: template<typename F> void f(F && lambda) { /* … */} Option #2 may, in some cases, be more efficient, as it can avoid a potential heap allocation for the embedded … Read more

What are the rules to govern underscore to define anonymous function?

Simple rules to determine the scope of underscore: If the underscore is an argument to a method, then the scope will be outside that method, otherwise respective the rules below; If the underscore is inside an expression delimited by () or {}, the innermost such delimiter that contains the underscore will be used; All other … Read more